开发者

Help with JavaScript regular expression

开发者 https://www.devze.com 2023-02-16 19:43 出处:网络
I need to check if a string starts with the following: \"+=\" I\'ve tried str.search(\"+=\")); 开发者_StackOverflow中文版

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消