DEV Community

Randy Rivera
Randy Rivera

Posted on

Using Capture Groups To Search and Replace

  • 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"));
Enter fullscreen mode Exit fullscreen mode
  • The replace call would return the string five 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);
Enter fullscreen mode Exit fullscreen mode
  • Here we wrote a regex fixRegex using three capture groups that will search for each word in the string one two three. Then we updated the replaceText variable to replace one two three with the string three two one and assigned the result to the result variable. Also we made sure that we are utilizing capture groups in the replacement string using the dollar sign ($) syntax.

Top comments (0)