Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex Matching Everything

I have this bit of Javascript,

if (/[A-Za-z0-9-]+/.test(sZip)) {
   alert(Match!);
}

and I'm using this as my test case "1234;"

I don't want "1234;" to be a match, I want only for example "1234" or "12 34" or "12-34" to match.

like image 856
exiva Avatar asked May 08 '26 21:05

exiva


2 Answers

/[A-Za-z0-9-]+$/

(The $ is the key: it means end of string, no more characters)

like image 108
Guillaume Avatar answered May 11 '26 10:05

Guillaume


Start the regular expression with ^ and end it with $. This way you tell it to match the whole string against the pattern. MDN docs.

If you want the space matched, you need to include it in the brackets. For space and dash to delimit alphanum fields, take this approach:

/^([A-Za-z0-9]+[ -])*[A-Za-z0-9]+$/
---^ 0 or more "ABC123-" fields
---------------^ separated by either dash or space
---------------------^ but at least once a "ABC123" field (no dash)
like image 23
Boldewyn Avatar answered May 11 '26 11:05

Boldewyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!