CocaCola
CocaCola

Reputation: 203

Pattern matching in Javascript

function validateFor9DigitNumber() {
  var txt = document.getElementById('<%= txt9Digit.ClientId %>');
  var textValue = parseInt(txt.value);
  var regSSN1 = new RegExp("^\d{9}$");
  if (isNaN(textValue))
      alert("Not a Number");
  else {
      alert("A Number");
      alert(regSSN1.test(textValue));
  }
}

I needed a Javascript function that would pattern match a text value for 9-digit number.

In the above needed function, I do land up in the else part and get the message "A Number", but then receive a FALSE for the next validation.

When I enter a 9-digit number say 123456789. I get FALSE even with egSSN1.match(textValue).

Where am I going wrong?

Upvotes: 1

Views: 3313

Answers (2)

Wayne
Wayne

Reputation: 60414

Avoid escaping issues in regular expression strings by using a regular expression literal:

/^\d{9}$/.test("123456789"); // true

Otherwise:

new RegExp("^\d{9}$").test("123456789"); // false (matches literal backspace)
new RegExp("^\\d{9}$").test("123456789"); // true (backslash escaped)

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76888

var regSSN1 = new RegExp("^\\d{9}$");

(Note the double backslash)

When using a literal string for a regex, you have to double-backslash.

You can also do:

var regSSN1 = /^\d{9}$/;

To avoid that problem.

Upvotes: 3

Related Questions