Find and Replace any string inside a string in Javascript

Find and Replace any string inside a string in Javascript.


There are a couple of ways you can do this. you can either use a regex pattern and find a match then replace the parts of the string or write a whole customized function in which using inbuilt string methods you can find and replace. But what I found the easiest to use is the below code:

var dummyString = "The king is dead, long live the king.";
var filteredString = dummyString.replace(/king/g, 'queen');
console.log(filteredString);


This will search all the occurrences of the searched part inside the main string and replace those. Check out the output here:

Find and Replace any string inside a string in Javascript


Happy coding!!

Comments