July 12, 2020
How to Replace all Occurrences of a String in Javascript
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
.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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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(); }); |