0

I am trying to validate strings with following pattern. starts with 3 digits followed by hyphen followed by 2 digits and ends with 4 digits. eg : 123-45-6789 I need to pass the pattern to a RegExp object as a string variable (I am getting the pattern value from a html element attribute ), hence I have escaped the RegExp with double slashes. To my surprise, I am seeing weird results.

var pattern = "^\\d{3}-\\d{2}-\\d{4}$";
var inputRegex = new RegExp(pattern, "g");
console.log(inputRegex.test('132-45-7899')); //True
console.log(inputRegex.test('132-45-7899')); //False
console.log(inputRegex.test('132-45-7899')); //True
console.log(inputRegex.test('132-45-7899')); //False

What am I doing wrong here? and what is the reason for this inconsistent results?

EDIT: Now I understood why the results are inconsistent , but my actual problem remained unsolved. HTML elem is like below

SCENARIO 1:

<input data-val-regexp="^\\d{3}-\\d{2}-\\d{4}$" id="ticketNumber">

var regexPattern = input.attr("data-val-regexp");
var inputRegex = new RegExp(regexPattern);
return inputRegex.test('123-45-6789'); // False

When I inspected, the inputRegex.source is "^\\d{3}-\\d{2}-\\d{4}$"

SCENARIO 2: If I assign the regexPattern with string literals everything works fine.

var pattern = "^\\d{3}-\\d{2}-\\d{4}$";
var inputRegex = new RegExp(pattern);
console.log(inputRegex.test('132-45-7899')); //True

In the above case inputRegex source value is "^\d{3}-\d{2}-\d{4}$"

Why is the backslash escaped in the second scenario, where as it didn't in the first scenario? What needs to be done in order to make scenario 1 work?

cweiske
  • 30,033
  • 14
  • 133
  • 194
DivideByzero
  • 474
  • 4
  • 15
  • You should open a new question with the actual problem, since that's not what you asked and this has been closed. But HTML doesn't do backslash-escaping; if you want a literal backslash inside a double-quoted string, just put a backslash. As it is, you're getting a regex looking for backslash-d instead of digits. – Mark Reed Dec 30 '15 at 01:03

1 Answers1

5

Because you're creating the regular expression with the g flag, it remembers where it left off and starts matching there, instead of at the beginning, the next time you call test. See Why does Javascript's regex.exec() not always return the same value?.

Community
  • 1
  • 1
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • thanks for the reference, I understood why the results are not consistent. My actual problem remained unsolved, please see my edit to this question. – DivideByzero Dec 30 '15 at 00:15