RegExp Methods # 02

Regular Expression Methods

Test() method

JavaScript has multiple ways to use regexes. One way to test a regex is using the .test() method. The .test() method takes the regex, applies it to a string (which is placed inside the parentheses), and returns true or false if your pattern finds something or not.

var stringText = "Mozahedul Islam is a good man and a programmer.";
var pattern = /good/;

/* test() method find the match between a regular 
expression and a specified string.return a boolean value. 
If it finds the match, then returns true. 
Otherwise returns false.
 */

var matchItem = pattern.test(stringText);
console.log(matchItem);
// return: true


exec() method

The exec() method executes a search for a match in a specified string and if any match is found, then returns a result array, or not found then returns null.


var stringText = 'Mozahedul Islam is a good man and a programmer. He is also good in mathematics'; var pattern = new RegExp('good', 'g'); var matchItem = pattern.exec(stringText); console.log(matchItem); // return 0: "good" groups: undefined index: 21 input: "Mozahedul Islam is a good man and a programmer. He is also good in mathematics" length: 1 [[Prototype]]: Array(0)


If we use the exec() method normally, then it will return only the first matching character or word. For this, we have to use this method within a loop like the below…


const str = 'Mozahedul Islam is a good and famous programmer. He is not only a good programmer but also a good human being.'; const reg = new RegExp('good', 'g'); var result = ''; let arr; while ((arr = reg.exec(str)) !== null) { // Reason for using arr[0]; // reg.exec() method will return an array // this array contains the matching character or word // as the first array item result += `${arr[0]} with index number ${reg.lastIndex}\n`; console.log(arr); } document.getElementById('regex').innerText = result;


Post a Comment

Previous Post Next Post