Replace all occurrences of a string in JavaScript?

To replace all occurrences of a string in JavaScript, you can use the replace() method in combination with a regular expression with the global (g) flag. Here's how you can do it:

const originalString = "Hello world, hello universe!"; const searchString = "hello"; const replacementString = "hi"; const modifiedString = originalString.replace(new RegExp(searchString, "g"), replacementString); console.log(modifiedString);

In this example, the replace() method is called on the originalString with a regular expression constructed using the new RegExp() constructor. The g flag is used in the regular expression to match all occurrences of the searchString. The replace() method then replaces all occurrences of the searchString with the replacementString.

replace() method

It's important to note that the replace() method returns a new string with the replacements made, and the original string remains unchanged. If you want to perform a case-insensitive replacement, you can use the i flag along with the g flag in the regular expression:

const originalString = "Hello World, hello Universe!"; const searchString = /hello/gi; const replacementString = "hi"; const modifiedString = originalString.replace(searchString, replacementString); console.log(modifiedString);

In this example, the i flag makes the replacement case-insensitive, so occurrences of "hello" with different capitalizations are all replaced.

Conclusion

Using the replace() method with a regular expression and the global flag is a powerful way to replace all instances of a string within another string.