Help with JavaScript regular expression
I need to check if a string starts with the following: "+="
I've tried
str.search("+="));
开发者_StackOverflow中文版
and
str.search("\+\="));
but get
Uncaught SyntaxError: Invalid regular expression: /+=/: Nothing to repeat
Can you help me with this, and also recommend a good resource for JavaScript regular expressions?
Try this regex:
/^\+=/.test(str);
It will return true
if the string starts with +=
. The ^
(caret) says "match from the beginning of the string". The +
needs to be escaped because it is a regex metacharacter that means "one or more of the preceding" (and that's not what we want).
You don't need a regex to test against a fixed substring. Just do this:
str.indexOf("+=")===0
The error you're getting is becaue +
has special meaning in a regex. It mean "the previous pattern is prepeated 1 or more times". Therefore, to search for a literal +
you need to escape the character using a backslash.
Also, to check its at the beginning of the string, start your regex with a ^
Therefore, the pattern you want is ^\+=
One option (among other) would be:
if(str.substr(0,2) == "+=")
And I think it would be the fastest if dealing with large strings.
精彩评论