简体   繁体   中英

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?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM