Replacing String Content

The replace() method replaces a specified value with another value in a string:

   str = "Please visit Microsoft!";
   var n = str.replace("Microsoft","W3Schools");

HTML file: Displayed by browser:
<body>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var txt = str.replace("Microsoft","W3Schools");
    document.getElementById("demo").innerHTML = txt;
}
</script>
</body>

Replace "Microsoft" with "W3Schools" in the paragraph below:

Please visit Microsoft!

The replace() method can also take a regular expression as the search value.

BackTable of ContentsNext