Home > Mobile >  Regex, how can I allow 10 or 11 digit number after slash?
Regex, how can I allow 10 or 11 digit number after slash?

Time:09-20

I am trying allow after slash 10 or 11 digit number. It must don't exist string anywhere after slash.

I tried:

let regCode = new RegExp('^[^\\da-zA-Z]*\\d{10,11}[^\\da-zA-Z]*$','g')
console.log(regCode.test("test/1234567890"))
console.log(regCode.test("test/1234567890abc"))
console.log(regCode.test("test/abc1234567a890abc"))

Thank you

CodePudding user response:

You can use the following regex defined with the help of a RegExp constructor notation (so as to avoid escaping /):

let regCode = new RegExp('/\\d{10,11}$')

Or, with a regex literal (to avoid escaping backslashes twice):

let regCode = /\/\d{10,11}$/

Surely, you can also use [0-9] instead of \\d in the first statement to avoid the "backslash hell".

Details:

  • / - a / char
  • \d{10,11} - ten or eleven digits
  • $ - end of string.

See the regex demo.

Note the absence of the global modifier in the regex, see Why does a RegExp with global flag give wrong results? to understand why.

See a JavaScript demo:

let regCode = new RegExp('/\\d{10,11}$');
console.log("test/1234567890 =>", regCode.test("test/1234567890"))
console.log("test/1234567890abc =>", regCode.test("test/1234567890abc"))
console.log("test/abc1234567a890abc =>", regCode.test("test/abc1234567a890abc"))

  • Related