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 aFALSE for the next validation.
When I enter a 9-digit number say 123456789. I get FALSE even withegSSN1.match(textValue).
Where am I going wrong?
2 Answers2
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.
Comments
Avoid escaping issues in regular expression strings by using a regular expression literal:
/^\d{9}$/.test("123456789"); // trueOtherwise:
new RegExp("^\d{9}$").test("123456789"); // false (matches literal backspace)new RegExp("^\\d{9}$").test("123456789"); // true (backslash escaped)Comments
Explore related questions
See similar questions with these tags.