#replace string
#programming
#webdevelopment
#javascript

How to replace all occurrences of a string in JavaScript?

Anonymous

AnonymousJan 14, 2024

In this article, We will see How to replace all occurrences of a string in JavaScript. There are the some following methods to replace all occurrences of a string in JavaScript:

Method 1: Using replace() method

To replace all occurrences of a string in JavaScript, you can use the replace() method along with a regular expression with the global flag (/g).

Here's an example:

let string = "Hello Hi Hello I am Jackson from Hello Techstackkit.com"
string = string.replace(/Hello/g, '');
console.log(string);

Output:

 Hi  I am Jackson from  Techstackkit.com

Method 2: Using split() and join() method

The split() method splits the string at each occurrence of "string" and creates an array of substrings. Then, the join() method is used to join the substrings back into a single string

Here's an example:

let string = "Hello Hi Hello I am Jackson from Hello Techstackkit.com";
string = string.split('Hello').join('');
console.log(string);

Output:

 Hi  I am Jackson from  Techstackkit.com

Method 3: Using replaceAll() method

You can use a regular expression with the replaceAll() method to replace all occurrences of "string" with an empty string. This method provides the search string and replacement value directly.

Here's an example:

let string = "Hello Hi Hello I am Jackson from Hello Techstackkit.com";
string = string.replaceAll('Hello', '');
console.log(string);

Output:

 Hi  I am Jackson from  Techstackkit.com

Happy Coding  😎