0

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

Dreams
  • 8,288
  • 10
  • 45
  • 71
  • Are you trying to match a phone number? (seems so, given that character set) You may want to see http://stackoverflow.com/questions/16699007/regular-expression-to-match-standard-10-digit-phone-number – Stephen P Oct 13 '16 at 17:55

5 Answers5

7

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')
mpen
  • 272,448
  • 266
  • 850
  • 1,236
5

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 thing

Mind you, "()" will match that regex. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

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'));
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

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

Ian Mundy
  • 376
  • 1
  • 8
0
/^[\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

Community
  • 1
  • 1
Jeetendra Chauhan
  • 1,977
  • 2
  • 15
  • 21