WebMasterCampus
WEB DEVELOPER Resources

Javascript Replace All Occurrences of a String

Learn how Javascript Replace All Occurrences of a String


Javascript Replace All Occurrences of a String

We can use a regular expression with the g flag. This will replace all occurence globally.

Example

<!DOCTYPE html>
<html>
<body>
  <div id="result"></div>
  <script>
    someString = 'webmastercampus helps professional to become valuable professional';
    anotherString = someString.replace(/professional/g, 'expert');

    document.getElementById("result").innerHTML = anotherString;
  </script>
</body>
</html>

Read more about Javascript Replace Method using regular expression

Created with love and passion.