Home Programs Replace All Occurrence of String Using RegEx in JavaScript

Replace All Occurrence of String Using RegEx in JavaScript

In this example we will replace a string in another string using JavaScript

This time will use regular expressions

We will define a string, then we will define t he word we want to replace and then use string.replace to replace that string with another one.

You will see that the regex below has the following /gi, this means

Flags Description
g Performs a global match (find all matches)
i Performs case-insensitive matching

Example 1

We are replacing the word red with blue

// replace all occurrence of a string
const string = 'A red bird was sitting on a red fence, is it a redpoll';

// regex expression
const regex = /red/gi;

// replace the characters
const newText = string.replace(regex, 'blue');

// display the result
console.log(newText);

When you run this you will see something like this

A blue bird was sitting on a blue fence, is it a bluepoll

You may also like