Startswith in javascript error

I am using startswith

reg exp in Javascript

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

      

but if I enter type characters , ] [ \ /

, Javascript throws an exception. Any idea?

+2


source to share


4 answers


If you are using regex you must make sure you pass in a valid Regular Expression to match (). Check the list of special characters to make sure you are not passing an invalid regexp. The following characters must always be escaped (put 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 (looks a little cleaner):

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

      



Next, you can add a startWith () method to your string prototype, which includes either of the above two solutions, to make the usage more readable:

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

      

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

words.startsWith( "word" );

      

+9


source


You can also use indexOf to determine if a string starts with a fixed value:



str.indexOf(prefix) === 0

      

+2


source


If you want to check if a string starts with a fixed value, you can also use substr

:

words.substr(0, string.length) === string

      

+1


source


If you really want to use regex, you need to avoid special characters in your string. PHP has a function for it, but I don't know what for JavaScript. Try using the following function I found from [Snipplr] [1]

function escapeRegEx(str)
{
   var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
   return str.replace(specials, "\\$&");
}

      

and use like

var mystring="Some text";
mystring=escapeRegEx(mystring);

      



If you need to find lines starting on a different line, try

String.prototype.startsWith=function(string) {
   return this.indexOf(string) === 0;
}

      

and use like

var mystring="Some text";
alert(mystring.startsWith("Some"));

      

+1


source







All Articles