How to use JavaScript Regex both literal notation and regexp object constructor method with examples
Regular Expressions provide a powerful way to extract information from text content. ? Regular Expressions or Regex can be used to search text and find matches on the search pattern. ? The returned results are the matches from the text on the search pattern provided.? The search pattern can get fairly complex, this chapter is designed to provide a simple introduction to extracting results from text blocks.
The regular expression patterns can be used within a number of JavaScript methods, to check for matches and do something within the code.? In JavaScript you can create the regular expression in two ways, either with a regular expression literal, where the pattern is nested between two forward slashes or using the constructor object which requires a pattern as a string argument.? If you expect the pattern to change or are receiving the pattern from an external source use the constructor.
https://youtu.be/DCnD10KjLYM
Regular expression literal
const myPattern1 = /a/;
RegExp constructor object
const myPattern2 = new RegExp('a');
Sample code for the different ways to write the expressions.
const myStr = 'Heallo World This is my new string for regular expressions new new new.';
const myPat1 = /new/g;
const myPat2 = new RegExp('new','g');
const myPat3 = new RegExp(/new/,'g');
const res1 = myStr.match(myPat1);
const res2 = myStr.match(myPat2);
const res3 = myStr.match(myPat3);
console.log(res1);
console.log(res2);
console.log(res3);
The results in the console are the same for each pattern