Basic Javascript Regex

I am trying to learn Javascript Regex and I ran into a problem.

I am trying to verify using the following rules.

Allow only:

Numbers 0-9 ( ) + - (space) 

I came up with the following expression:

 /[0-9\)\(\+\- ]+/i 

The following matches, but should not, because they contain the @ character:

 +0@122 0012 

I use below to check: (returns true)

 /[0-9\)\(\+\- ]+/i.test(" +0@122 0012") 

Thanks.

+6
source share
1 answer

Your regular expression will not match the @ symbol, but it is not necessary to call .test() to return true . There just should be a match somewhere on the line.

If you want to insist that the whole line matches, you must use the ^ and $ bindings.

 /^[0-9)(+ -]+$/i.test(" +0@122 0012") 
+15
source

Source: https://habr.com/ru/post/973108/


All Articles