Below is my regex but it seems not working
/[0-9\-\(\)]/.test(str)
when I test
/[0-9\-\(\)]/.test('(12321)213213d')
It will return true
Below is my regex but it seems not working
/[0-9\-\(\)]/.test(str)
when I test
/[0-9\-\(\)]/.test('(12321)213213d')
It will return true
What you're actually testing is if any of those characters are in your test string. You want to check if it contains only those characters. To do that, you need to say from start ^
to finish $
it only contains those chars.
e.g.
/^[0-9()-]+$/.test('(12321)213213d')
Your current regex just checks that any one character in the string matches the character class. Add anchors and a quantifier: /^[0-9\-\(\)]+$/
^
- "Beginning of input" anchor$
- "End of input" anchor+
- Require one or more of the preceding thingMind you, "()"
will match that regex. :-)
You need to repeat it with either *
or +
. You also need to anchor it with ^
and $
to contain the whole string.
console.log(/^[0-9\-\(\)]+$/.test('(12321)213213d'));
console.log(/^[0-9\-\(\)]+$/.test('(12321)213213'));
I believe adding input beginning/end characters will fix this. Like
^[0-9\-(\)]$/.exec('(12321)213213d')
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
/^[\d\(\)\-]+$/.test('(12321)213213d')
^ start, $ end, \d for digit and ()-,
I think you are looking for telephone number matcher, if your answer is yes then this is not right regex for it.
for telephone matcher visit this link