How to Replace All Occurences of a String in Javascript?


In JavaScript, you can replace all occurrences of a string using the replace() method with the regular expression (regex) global modifier /g.

Here is an example using the replace() method and regex /g modifier to replace all occurrences of a string:

let myString = "Hello World, Hello World";

// Replace "Hello" with "Hi" globally using regex /g modifier
let replacedString = myString.replace(/Hello/g, "Hi");

console.log(replacedString); // "Hi World, Hi World"

In this example, the replace() method replaces all occurrences of the string "Hello" with "Hi" by adding the /g regex global modifier at the end of the regular expression pattern.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?