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:
replace()
methodTo replace all occurrences of a string in JavaScript, you can use the replace()
method along with a regular expression with the global flag (/g)
.
let string = "Hello Hi Hello I am Jackson from Hello Techstackkit.com"
string = string.replace(/Hello/g, '');
console.log(string);
Hi I am Jackson from Techstackkit.com
split()
and join()
methodThe 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
let string = "Hello Hi Hello I am Jackson from Hello Techstackkit.com";
string = string.split('Hello').join('');
console.log(string);
Hi I am Jackson from Techstackkit.com
replaceAll()
methodYou 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.
let string = "Hello Hi Hello I am Jackson from Hello Techstackkit.com";
string = string.replaceAll('Hello', '');
console.log(string);
Hi I am Jackson from Techstackkit.com