Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

startswith in javascript error

I'm using startswith reg exp in Javascript

if ((words).match("^" + string)) 

but if I enter the characters like , ] [ \ /, Javascript throws an exception. Any idea?

like image 674
Santhosh Avatar asked Aug 30 '26 02:08

Santhosh


2 Answers

If you're matching using a regular expression you must make sure you pass a valid Regular Expression to match(). Check the list of special characters to make sure you don't pass an invalid regular expression. The following characters should always be escaped (place a \ before it): [\^$.|?*+()

A better solution would be to use substr() like this:

if( str === words.substr( 0, str.length ) ) {
   // match
}

or a solution using indexOf is a (which looks a bit cleaner):

if( 0 === words.indexOf( str ) ) {
   // match
}

next you can add a startsWith() method to the string prototype that includes any of the above two solutions to make usage more readable:

String.prototype.startsWith = function(str) {
    return ( str === this.substr( 0, str.length ) );
}

When added to the prototype you can use it like this:

words.startsWith( "word" );
like image 79
Huppie Avatar answered Sep 01 '26 16:09

Huppie


One could also use indexOf to determine if the string begins with a fixed value:

str.indexOf(prefix) === 0
like image 26
Catogeorge Avatar answered Sep 01 '26 16:09

Catogeorge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!