How to Replace all Occurrences of a String in Javascript

  • 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">
  <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">
  <div class="container">
    <div class="content"></div>

  <script src="script.js"></script>
.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;

    outline: none;
    padding: 10px 20px;
    margin: 5px;


  • 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;


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

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