How To

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 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

5 years ago

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++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago