Quantifiers in regex determine the quantity of a character. Quantifiers are written in Curly Brackets{}. How many times does a character appear in a string so that it matches the expression. This work can only be done by Quantifiers.


RegEx (Regular Expression) Quantifiers In JavaScript - 4


RegEx Quantifiers

Some examples based on Quantifiers are as follows:

Example 1 : In this example, we set the quantity of d character as two. If d occurs twice in the string, the string will match.


let regex = /cod{2}exradar/; // d occurs two times

let string = "coddexradar";

let result = regex.exec(string);

if(regex.test(string)) {

console.log(result);

console.log(`The string "${string}" matches the expression "${regex.source}"`);

}else {

console.log(`The string "${string}" does not match the expression "${regex.source}"`);

code-box


Output : The string "coddexradar" matches the expression "cod{2}exradar"


Example 2 : Through quantifiers we can set the range of a character. In this example, we have set the d character range from 0 to 2. If this character occurs more than this range then the string will not match.


let regex = /cod{0,2}exradar/; // d occurs exaclty 0 to 2 (0, 1, 2) times

let string = "codexradar";

let result = regex.exec(string);

if(regex.test(string)) {

console.log(result);

console.log(`The string "${string}" matches the expression "${regex.source}"`);

}else {

console.log(`The string "${string}" does not match the expression "${regex.source}"`);

code-box


Output : The string "codexradar" matches the expression "cod{0,2}exradar"


Summary

In this post, we learned about quantifiers of regular expressions in JavaScript. Now you practice this. Keep visiting the blog to read more new similar posts.

Post a Comment

Previous Post Next Post