How to Replace All Words in a String Using JavaScript

We can use replace() function in JavaScript to replace all the words in the given string.

replace() method in JavaScript

replace() method searches for a specified word or value in the string and returns output as a new string with replaced value.

By default replace() method repaces just one value.

So, we need to use “g” regular expression modifier to replace all values in the string.

Example:

<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

We can also use “i” regular expression modifier with “g” to match case-insensitive words and replace all.

Example:

<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

Leave a Reply

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

Read previous post:
download turbo c++
Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++ program C++ programming is one...

Close