How to replace all occurrences of a string in JavaScript

Generally, we use the replace() function to replace the particular word phrase. This does not work for replacing all occurrences of a string. i.e replace() is replaces only first matching word phrase only.

For example "How to replace all occurrences of a string in JavaScript".
Here I want to replace the space with "-" 'in all occurrences. Now I use the replace().
var title = "How to replace all occurrences of a string in JavaScript";
var result = title.replace(" ", "-");
console.log(result);
//How-to replace all occurrences of a string in JavaScript
Now my result is How-to replace all occurrences of a string in JavaScript
Here replace() is just replaces the word phrase only once. You have to replace all occurrences of a string. Use the custom function findAndReplace().
function findAndReplace(string, target, replacement) {
 var i = 0, length = string.length;
 for (i; i < length; i++) {
   string = string.replace(target, replacement);
 }
 return string;
}
var title = "How to replace all occurrences of a string in JavaScript";
var result = findAndReplace(title, " ", "-");
console.log(result);
//How-to-replace-all-occurrences-of-a-string-in-JavaScript

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff


EmoticonEmoticon