July 12, 2020
How to Replace all Occurrences of a String in Javascript
To better understand the above scenario, think of a string that contains multiple occurrences of a color name such as red and now you want to replace red with blue. This can be a bit tricky to do so if you are new to javascript.
There are multiple solutions to the above problem. My recommended best solution is to use regex with
replace()
method. It is fast and easy to use in comparison to other solutions.In the following example, we have one global string and this string contains the
“happy”
word multiple times. I just want to replace it with “sad”
and display it on the screen. Please have a look over the code example and steps given below.HTML & CSS
- We have 3 elements in the HTML file (2
div
and 1button
). The outerdiv
element with a class ofcontainer
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 ofcontent
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 thehead
element. - We have also included our javascript file
script.js
with ascript
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 innerdiv
element. We are calling this method in the next line. - We have selected the
button
element using thedocument.querySelector()
method and stored it inbtnReplace
variable. - We have attached the
click
event listener to thebutton
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”
. Thisreplace()
method will return a string. - We are calling the
showSentence()
method to update the inner text of the innerdiv
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(); });