In this article you will learn how to replace all instances of a substring with another string in a given string using JavaScript. There are following ways to replace single occurrence or all occurrences of a string in JavaScript.
replace single occurrence using JavaScript:
To replace a single occurrence of a substring in a string in JavaScript, you can use the replace()
method without the global flag 'g' .
What is replace() method in JavaScript? the replace()
method is a built-in method of strings that can be used to replace a specific substring with another substring. The replace()
method takes two arguments: the first argument is the substring you want to replace, and the second argument is the replacement substring.
syntax:
replace(regexp, newSubString)
replace(subString, newSubString)
following is an example of using the replace()
method to replace the first occurrence of the word "cat" with the word "dog":
let originalString = "The cat in the hat cat.";
let newString = originalString.replace(/cat/, "dog");
console.log(newString); // "The dog in the hat cat."
You can also use the slice()
method to get the first occurrence of a substring, and then concatenate it with the remaining string:
let originalString = "The cat in the hat cat.";
let index = originalString.indexOf("cat");
let newString = originalString.slice(0, index) + "dog" + originalString.slice(index + 3);
console.log(newString); // "The dog in the hat cat."
Note that the first argument of the indexOf()
method is the string you want to find, and the second argument is the starting index of the search.
Replace All String Occurrences in JavaScript:
In JavaScript, you can use the replace()
method on strings to replace all occurrences of a specific substring with another substring. The replace()
method takes two arguments: the first argument is the substring you want to replace, and the second argument is the replacement substring.
You can use a string or a regular expression as the first argument, and it will replace the first occurrence of the match, if you want to replace all the occurrences you need to use a regular expression with the global flag 'g'
Here is an example of using the replace()
method to replace all occurrences of the word "cat" with the word "dog":
let originalString = "The cat in the hat.";
let newString = originalString.replace(/cat/g, "dog");
console.log(newString); // "The dog in the hat."
Note that the first argument is a regular expression with the global flag 'g'
there is an other way to achieve the same result is to use a function as the second argument to replace method in the following example we replace all capitals (A) with small character (a)
let originalString = "The cat in the hat.";
let newString = originalString.replace(/cat/g, function(match){
return "dog";
});
console.log(newString); // "The dog in the hat."
It will replace all the matched pattern in the string with the returned value from the function please see the following screenshot