Thursday, September 13, 2018

JavaScript - Built in Feature - Regular Expressions

Regular Expressions are patterns used to match character combination in strings. Below are some examples:

var myString = "a quick brown fox jumped over the lazy dog";
console.log(myString);

var myPattern = /fox/;
console.log(myPattern);

console.log(myPattern.exec(myString));
console.log(myPattern.test(myString));
console.log(myString.match(myPattern));
console.log(myString.search(myPattern));

Console Output:

  • "a quick brown fox jumped over the lazy dog"
  • [object RegExp] { ... }
  • ["fox"]
  • true
  • ["fox"]
  • 14

Regular expressions are a science of their own. There are a lot of special characters you can use to build complex queries.

Consider the following stackoverflow question:
https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript

Without regular expressions, you would have to loop through each character in the string to search for patterns. Using pattern matching with regular expressions makes this problem simple. The pattern does look difficult. But, we can google for help. Also, we we know it, then the difficulty reduces. It is quick as it offers a great performance and it is a one liner. You do not have to write multiple nested loops to acheive the same with slower performance.

The 3 important methods in Regular expressions:

  • exec
  • test
  • match


Refer:



Practice at:

No comments:

Post a Comment