replace()
replace() method takes two arguments, the first argument is which character(s) or word do we wanna change, and the second argument is by which argument we wanna change.
const reg = new RegExp("Mozahedul", "i"); const str = "Mozahedul Islam is a good programmer"; console.log(reg); // Return: // /Mozahedul/i const result = str.replace(reg, "Rafiqul"); console.log(result); // Return: // Rafiqul Islam is a good programmer
match() method
So far, we have only been checking if a pattern exists or not within a string with the .test() method. We can also extract the actual matches you found with the .match() method.
To use the .match() method, apply the method on a string and pass in the regex inside the parentheses.
Here's an example:
"Hello, World!".match(/Hello/); let ourStr = "Regular expressions"; let ourRegex = /expressions/; ourStr.match(ourRegex);
Here the first match would return ["Hello"] and the second would return ["expressions"]. Note that the .match syntax is the "opposite" of the .test method you have been using thus far:
'string'.match(/regex/); /regex/.test('string');
Post a Comment