Out of the different “Data Types” in JavaScript, String has been one of my favorites. It is also one of the most widely used Data Type. It would not be an understatement to say that most of our programming activities revolve around some kind of string. Many a times you would come across scenarios in JavaScript to replace all occurrences of a string.  In JavaScript there are various native built in string related methods however there is no JavaScript replace all method predefined. Instead, String.replace() is a very common method that most of us would have used. Lets take a look at it.

The syntax of String.replace() is :

In the syntax above, the “string” refers to the String object that you want to execute the “replace” method on, “searchvalue” refers to the word / character that you want to look for and replace within the string, and the “newvalue” refers to the new word/character that you want to replace the “searchvalue” with.

Lets look at an example of the Default behaviour :

However, if you notice the second occurrence of “john” was not replaced. That is exactly what the replace method does. It by default replaces only the first occurrence of the string to be replaced or the search string.

Then, How do we search and replace all the occurrences of a string in JavaScript? Is there a JavaScript replace all method? – Resolved !

Well, there isn’t any JavaScript replace all method available out of the box but a JavaScript replace all regex is available. To search and replace all the occurrences of a string in JavaScript using the string.replace() method, you’ll have to pass the search string as a regular expression. For example :

Also since the search is case sensitive, we had to pass the “i” parameter in the regular expression along with the “g” parameter to make the search case-insensitive. You may consider reading more about regular expressions, they are extremely useful.

jQuery string replace all

Even in jQuery replace all string or replace text in jQuery or a replaceall jquery can be done using the same method. All you need to do is to access the string value using one of the jQuery Selectors and run it through the regex mentioned in the example above.

You may use the above mentioned method to do a JavaScript replace all spaces in string, JavaScript replace all quotes , or to do a JavaScript replace all dots/periods in JavaScript string. Also, you may use the same method to do a JavaScript replace all occurrences of a string in jquery or to try a JavaScript replace all commas. Please remember to use the JavaScript replace all regex to match and replace as per your requirement. Hope you liked our article on JavaScript Replace all occurrences.