以javascript错误开头

San*_*osh 2 javascript regex

startswith在Javascript中使用reg exp

if ((words).match("^" + string)) 
Run Code Online (Sandbox Code Playgroud)

但如果我输入字符, ] [ \ /,Javascript会抛出异常.任何的想法?

Hup*_*pie 9

如果使用正则表达式进行匹配,则必须确保传递有效的正则表达式以匹配().检查特殊字符列表以确保不传递无效的正则表达式.应始终转义以下字符(在其前面放置\):[\ ^ $.|?*+()

更好的解决方案是使用substr(),如下所示:

if( str === words.substr( 0, str.length ) ) {
   // match
}
Run Code Online (Sandbox Code Playgroud)

或使用indexOf的解决方案是一个(看起来更清洁):

if( 0 === words.indexOf( str ) ) {
   // match
}
Run Code Online (Sandbox Code Playgroud)

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 ) );
}
Run Code Online (Sandbox Code Playgroud)

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

words.startsWith( "word" );
Run Code Online (Sandbox Code Playgroud)

  • 不要使用`indexOf`.它搜索整个字符串而不仅仅是开头. (3认同)