Reputation: 407
Hello I have a problem create regular expression (phone number) for the following conditions:
the finally format must be:
+421 xxx xxx xxx
or +420 xxx xxx xxx
I've created something like this so far, but I have no idea how to proceed.
const regexPhone = /^\+[0-9]{12}/i;
Can you help me please?
Upvotes: 0
Views: 349
Reputation: 1598
Regex patterns are often created on the basis of how the text 'looks', like in your example the numbers should look like "+420 xxx xxx xxx", so why not make regex for this exact format?
Try this: /^\+42[10] \d{3} \d{3} \d{3}$/
let pattern = /^\+42[10] \d{3} \d{3} \d{3}$/
let s = "+421 543 100 478"
console.log(pattern.test(s))
Now you can simplify the above regex to /^\+42[10]( \d{3}){3}$/
^ matches the start of the string
\+ matches +
42[10] matches 42 followed by either 1 or 0
( \d{3}){3} matches a space followed by three digits, this inturn is matched exactly three times
$ matches the end of the string
Upvotes: 1