Skip to content

JavaScript replace regex capture group

  • by

You can make searching even more powerful when it also changes (or replaces) the text you match. Use replace() on a string where first parameter the regex pattern you want to search for. You can also access capture groups in the replacement string with dollar signs ($).

JavaScript replace regex capture group

Simple example code 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.

<!DOCTYPE html>
<html>
<body>
  <script>
    let str = "one two three";
    let fixRegex = /(\w+)\s(\w+)\s(\w+)/; 
    
    let replaceText = "$3 $2 $1"; 
    let res = str.replace(fixRegex, replaceText);

    console.log(res)

  </script>
</body>
</html>

Output:

JavaScript replace regex capture group

Source: https://dev.to/rthefounding/using-capture-groups-to-search-and-replace-5bhc

Do comment if you have any doubts or suggestions on this JS replace topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading