I need a regular expression for JavaScript that will match any string that does not start with the +
character. With one exception, strings starting with +1
are okay. The empty string should also match.
For example:
"" = true
"abc" = true
"+1" = true
"+1abc" = true
"+2" = false
"+abc" = false
So far I have found that ^(\+1|[^+]?)$
takes care of the +1
part but I cannot seem to get it to allow more characters after without invalidating the first part. I thought that ^(\+1|[^+]?).*?$
would work but it seems to match everything.
First, the second part of your matching group isn't optional, so you should remove the ?.
Second, since you only care about what shows up at the beginning, there's no need to test the whole string until the $.
Lastly, to make the empty string return true you need to test for /^$/ as well.
Which turns out to:
/^(\+1|[^+]|$)/
For example:
/^(\+1|[^+]|$)/.test(""); // true
/^(\+1|[^+]|$)/.test("abc"); // true
/^(\+1|[^+]|$)/.test("+1"); // true
/^(\+1|[^+]|$)/.test("+1abc"); // true
/^(\+1|[^+]|$)/.test("+2"); // false
/^(\+1|[^+]|$)/.test("+abc"); // false
(console should be open)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With