javascript replace all instances in a string

/ Published in: JavaScript
Save to your folder(s)

Normal replace() function only replaces first instance.

Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2. var visitorName = "Chuck";
  3. var myOldString = "Hello username! I hope you enjoy your stay username.";
  4. var myNewString = myOldString.replace(/username/g, visitorName);
  6. document.write("Old string = " + myOldString);
  7. document.write("<br />New string = " + myNewString);
  9. </script>


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.