How to replace all occurrences of a string in JavaScript

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the JavaScript replace() Method

You can use the JavaScript replace() in combination with the regular expression to find and replace all occurrences of a word or substring inside any string, like this:

  • <script type="text/javascript">
  •     var myStr = 'freedom is not worth having if it does not include the freedom to make mistakes.';
  •     var newStr = myStr.replace(/freedom/g, "liberty");
  •     
  •     // Printing the modified string
  •     document.write(newStr);
  • </script>

However, if the string comes from unknown/untrusted sources like user inputs, you must escape it before passing it to the regular expression. The following example will show you the better way to find and replace a string with another string.

  • <script type="text/javascript">
  • /* Define function for escaping user input to be treated as 
  •    a literal string within a regular expression */
  • function escapeRegExp(string){
  •     return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  • }
  •  
  • /* Define functin to find and replace specified term with replacement string */
  • function replaceAll(str, term, replacement) {
  •   return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);
  • }
  •  
  • /* Testing our replaceAll() function  */
  • var myStr = 'if the facts do not fit the theory, change the facts.';
  • var newStr = replaceAll(myStr, 'facts', 'statistics')
  •  
  • // Printing the modified string
  • document.write(newStr);
  • </script>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.