JavaScript Regex Replace

To replace words using regular expressions in JavaScript, you can utilize the replace() method along with a regex pattern. Here’s an example:

var str = "Hello, world! Hello, universe!";
var regex = /Hello/g;
var replacement = "Hi";
var result = str.replace(regex, replacement);

console.log(result); // Output: Hi, world! Hi, universe!

In this example, we have a string str containing multiple occurrences of the word “Hello”. We define a regex pattern /Hello/g to match all occurrences of the word “Hello” globally. The g flag is used to perform a global search.

The replace() method is called on the str string and takes the regex pattern as the first argument and the replacement string "Hi" as the second argument. The replace() method then replaces all matches of the regex pattern with the replacement string.

The resulting string with the replacements is stored in the result variable, and when we log it to the console, we get the output "Hi, world! Hi, universe!".

You can modify the regex pattern to match different words or patterns based on your specific requirements. Additionally, you can use more complex regex patterns and even use capturing groups to perform advanced replacements.

Here’s an example that demonstrates the use of a capturing group in the regex pattern:

var str = "John Doe, Jane Smith";
var regex = /(\w+)\s(\w+)/g;
var replacement = "$2, $1";
var result = str.replace(regex, replacement);

console.log(result); // Output: Doe, John Smith, Jane

In this example, the regex pattern (\w+)\s(\w+) captures two words separated by a space. The replacement string "$2, $1" swaps the order of the captured words and adds a comma between them. As a result, the output is "Doe, John Smith, Jane", where the names are rearranged.

Regular expressions provide powerful pattern matching and replacement capabilities in JavaScript, allowing you to perform various transformations on strings.