JavaScript pattern matching using Regular Expression(RegEx)

If we want to match special character, meta character or using quantifers , we can do that by regular expression. For eg. If we want to match date , time or any particular pattern or complex things we can use it.

Regular expressions allow you to check a string of characters like an e-mail address or password for patterns, to see so if they match the pattern defined by that regular expression and produce actionable information.

For eg: If we want to match a 10 digit number

var regex = /^\d{10}$/;
console.log(regex.test('9995484545'));
// true

Let’s break that down and see what’s going on up there.

  1. If we want to enforce that the match must span the whole string, we can add the quantifiers ^ and $. The caret ^ matches the start of the input string, whereas the dollar sign $ matches the end. So it would not match if string contain more than 10 digits.
  2. \d matches any digit character.

3. {10} matches the previous expression, in this case \d exactly 10 times. So if the test string contains less than or more than 10 digits, the result will be false.

Eg: If we want to match a date like pattern (DD-MM-YY)

var regex = /^(\d{1,2}-){2}\d{2}(\d{2})?$/;
console.log(regex.test('01-01-1990'));
// true
console.log(regex.test('01-01-90'));
// true
console.log(regex.test('01-01-190'));
// false

So the following steps follows:

  1. Again, we have wrapped the entire regular expression inside and $, so that the match spans entire string.
  2. ( start of first subexpression.
  3. \d{1,2} matches at least 1 digit and at most 2 digits.
  4. - matches the literal hyphen character.
  5. ) end of first subexpression.
  6. {2} match the first subexpression exactly two times.
  7. \d{2} matches exactly two digits.
  8. (\d{2})? matches exactly two digits. But it’s optional, so either year contains 2 digits or 4 digits.

Leave a comment

Your email address will not be published. Required fields are marked *