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.
let myStr = "one two three"; let oneRegex = /one/; console.log(str.replace(oneRegex, "five"));
replacecall would return the string
five two three
You can also access capture groups in the replacement string with dollar signs (
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 string
one two three. Then we updated the
replaceTextvariable to replace
one two threewith the string
three two oneand assigned the result to the
resultvariable. Also we made sure that we are utilizing capture groups in the replacement string using the dollar sign (