How to Replace all Occurrences of a String in Javascript

In this video tutorial, you will learn how to replace all occurrences of a string in javascript.

HTML:

<!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>

 

CSS:

.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:

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();
});

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •