We can use the replace() function in JavaScript to replace all the given string words.
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
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 🙂
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…