We can use the replace() function in JavaScript to replace all the given string words.
JavaScript replace() Method
replace() method searches for a specified word or value in the string and returns the output as a new string with replaced value.
By default replace() method repaces just one value.
So, we need to use the “g” regular expression modifier to replace all values in the string.
Example 1
<script type="text/javascript">
var Str = 'random is not so random';
var newString = Str.replace(/random/g, "dumb");
document.write(newString);
</script>
Output
dumb is not so dumb
Read Also: How To Open Link In New Tab HTML
We can also use the “i” regular expression modifier with “g” to match case-insensitive words and replace all.
Example 2
<script type="text/javascript">
var Str = 'Random is not so random';
var newString = Str.replace(/random/gi, "hard");
document.write(newString);
</script>
Output
hard is not so hard
Conclusion
I hope now you know how to replace all words in string using JavaScript. Also, JavaScript provides many other functions to perform complex tasks.
Enjoy Scripting π