2

I need to check if a string starts with the following: "+="

I've tried

str.search("+="));

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?

4 Answers 4

9

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).

Sign up to request clarification or add additional context in comments.

Comments

5

You don't need a regex to test against a fixed substring. Just do this:

str.indexOf("+=")===0

Comments

4

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 ^\+=

Comments

3

One option (among other) would be:

if(str.substr(0,2) == "+=")

And I think it would be the fastest if dealing with large strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.