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
replace
call would return the stringfive two three
You 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
fixRegex
using three capture groups that will search for each word in the stringone two three
. Then we updated thereplaceText
variable to replaceone two three
with the stringthree two one
and assigned the result to theresult
variable. Also we made sure that we are utilizing capture groups in the replacement string using the dollar sign ($
) syntax.
Top comments (0)