简体   繁体   English

以javascript错误开头

[英]startswith in javascript error

I'm using startswith reg exp in Javascript 我在Javascript中使用startswith reg exp

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

but if I enter the characters like , ] [ \\ / , Javascript throws an exception. 但是如果我输入像, ] [ \\ /这样的字符,Javascript会抛出异常。 Any idea? 任何想法?

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: 更好的解决方案是使用substr(),如下所示:

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

or a solution using indexOf is a (which looks a bit cleaner): 或使用indexOf的解决方案是一个(看起来更清洁):

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: 接下来,您可以将startsWith()方法添加到包含以上两种解决方案中的任何一种的字符串原型中,以使用法更具可读性:

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" );

也可以使用indexOf来确定字符串是否以固定值开头:

str.indexOf(prefix) === 0

如果要检查字符串是否以固定值开头,您还可以使用substr

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

If you really want to use regex you have to escape special characters in your string. 如果你真的想使用正则表达式,你必须转义字符串中的特殊字符。 PHP has a function for it but I don't know any for JavaScript. PHP有它的功能,但我不知道任何JavaScript。 Try using following function that I found from [Snipplr][1] 尝试使用我从[Snipplr] [1]中找到的以下功能

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

and use as 并用作

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



If you only need to find strings starting with another string try following 如果您只需要查找以其他字符串开头的字符串,请尝试以下操作

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

and use as 并用作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM