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);
  5.  
  6. document.write("Old string = " + myOldString);
  7. document.write("<br />New string = " + myNewString);
  8.  
  9. </script>

URL: http://www.tizag.com/javascriptT/javascript-string-replace.php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.