Searching is useful. However, you can make searching even more powerful when it also changes (or replaces) the text you match.
You can search and replace text in a string using
.replace()on a string. The inputs for.replace()is first the regex pattern you want to search for. The second parameter is the string to replace the match or a function to do something.Ex:
let myStr = "one two three";
let oneRegex = /one/;
console.log(str.replace(oneRegex, "five"));
The
replacecall would return the stringfive two threeYou can also access capture groups in the replacement string with dollar signs (
$).Ex:
let str = "one two three";
let fixRegex = /(\w+)\s(\w+)\s(\w+)/;
let replaceText = "$3 $2 $1";
let result = str.replace(fixRegex, replaceText);
- Here we wrote a regex
fixRegexusing three capture groups that will search for each word in the stringone two three. Then we updated thereplaceTextvariable to replaceone two threewith the stringthree two oneand assigned the result to theresultvariable. Also we made sure that we are utilizing capture groups in the replacement string using the dollar sign ($) syntax.
Top comments (0)