How to Replace All Words in a String Using JavaScript

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

Also read: JavaScript array methods explained with examples

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 πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
Scroll to bottom of the page using jQuery
Scroll to the Bottom of the Page Using jQuery

Here is the simple example to scroll to the bottom of the page with jQuery. HTML code jQuery Also read:...

Close