How To Replace String in Javascript Using replace() and replaceAll() Method

In this blog post, we will replace a string with another string. Here we are going to use str.replace() and replaceAll() method of javascript.

And in the second step, we will replace all the same strings of a paragraph with another string.

So let’s started.

HTML

<h2>Replace string in Javascript</h2>
<p id="string_id">Hello, Developer</p>
<button onclick="myFunction()">Replace String</button>

Javascript

<script>
function myFunction() {
    let str = document.getElementById("string_id").innerHTML; 
    document.getElementById("string_id").innerHTML = str.replace("Developer", "Codermen");;
}
</script>

Replace All Occurrences of a String in JavaScript

Now we have a string. In which the word “Lorem” has come many times. We will replace all “Lorem” words with “code” by str.replaceAll() method. just flow the code.

HTML

 <h2>Replace string in Javascript</h2>

    <p id="string_id">What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has?
    </p>

<button onclick="myFunction()">Replace String</button>

Javascript

<script>
function myFunction() {
    let str = document.getElementById("string_id").innerHTML; 
    document.getElementById("string_id").innerHTML = str.replaceAll('Lorem', 'Code');
}
</script>

I hope this code will help you.