Startswith in javascript error
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" );
source to share
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"));
source to share