Replace all occurrences of a string in JavaScript
Today we will show you how to replace all occurrences of a string in JavaScript. Here we show you the simplest way to replace all instances of string via a single line of code.
How to replace all occurrences of a string in JavaScript, javascript replace all spaces, string replace in javascript, javascript string replace multiple, How to replace all dots in a string using JavaScript.
Checkout our previous articles on React JS
Javascript replace() method replaces only the first occurrence of the string. There are several methods are available to replace all occurrences of a string in JavaScript. But we will discuss only two methods in this article.
Demo & Source Code
Github RepositoryWay to Replace all occurrences of a string in JavaScript
- JavaScript string replace method with regular expression
- JavaScript split and join method
1. JavaScript string replace method with regular expression
Here we have to use regular expressions to replace all words or string via a single line. We will use g
flag (global) instead of normal string character as a regular expression.
Below is a small example where we will replace “–” instead of “is”.
1 2 3 4 5 | function handleReplaceAll() { var sentence = 'This is test example and it Is easy to learn.'; var output = sentence.replace(/is/g, '-'); // Output: Th- - test example and it Is easy to learn. document.getElementById("demo").innerHTML = output; } |
Now if you want to replace the case insensitive string then you have to use gi
flag. Checkout the below example.
1 2 3 4 5 | function handleReplaceAllCI() { var sentence = 'This is test example and it Is easy to learn.'; var output = sentence.replace(/is/gi, '-'); // Output: Th- - test example and it - easy to learn. document.getElementById("demo1").innerHTML = output; } |
2. JavaScript split and join method
Another simplest way to replace all is to use Split and Join method.
1 2 3 4 5 | function handleReplaceAllSplitJoin() { var sentence = 'This is test example and it Is easy to learn.'; var output = sentence.split('is').join('-'); // Output: Th- - test example and it Is easy to learn. document.getElementById("demo2").innerHTML = output; } |