How to Replace all Occurrences of a String in Javascript

In this tutorial, you will learn how to replace all occurrences of a string in javascript. It is not very common for a string to contain multiple occurrences of the same text.  However, we could still encounter such situations and now we want to replace that text with some other text.
  • We have 3 elements in the HTML file (2 div and 1 button). The outer div element with a class of container is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Replace”.
  • The inner div element with a class of content is empty. We will populate this with javascript.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  
  <div class="container">
    <button>Replace</button>
    <div class="content"></div>
  </div>

  <script src="script.js"></script>
</body>
</html>
.container, .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.content {
    font-size: 1.8rem;
    padding: 10px;
    margin-top: 10px;
    width: 50%;
    border: 1px solid black;
    min-height: 100px;
}

button{
    outline: none;
    padding: 10px 20px;
    margin: 5px;
}

Javascript

  • We have a global variable sentence and it holds a long string as its value.
  • We have created the showSentence() method. This method will set our global string as an inner text of the inner div element.  We are calling this method in the next line.
  • We have selected the button element using the document.querySelector() method and stored it in btnReplace variable.
  • We have attached the click event listener to the button element.
  • Inside the event handler function, we are calling replace() method and passing regex /happy/g as the first parameter and “sad” as the second parameter. It will find all occurrences of “happy” and replace them with “sad”. This replace() method will return a string.
  • We are calling the showSentence() method to update the inner text of the inner div element.
let sentence = 'I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy.';

function showSentence(){
    document.querySelector('.content').innerText = sentence;
}

showSentence();

let btnReplace = document.querySelector('button');

btnReplace.addEventListener('click', () =>{
    sentence = sentence.replace(/happy/g, 'sad');
    showSentence();
});