String.replace method in javascript does not replace every occurrence of the string, it only replaces the first occurrence. To replace all occurrences of the string you must provide the replace() method a regular expression (or pass search string as a regular expression).
Use g regular expression modifier to make a global search for the string (performs a global match). Also make your search case sensitive by using i modifier.
In the below code search is also case sensitive we had to pass the i parameter in the regular expression along with the g parameter.
Here is the example code:
<p id=egstring">Sonia is making an application in angularjs and sonia is enjoying learning it.</p>
<button onclick="myReplaceFunc()">Replace sonia with she</button>
Below is the code for your js file:
function myReplaceFunc(){
var egstring = document.getElementById('egstring').innerHTML;
/*Replace every occurrence of Sonia, case insensitive with She and store into a new variable named Newegstring. */
var Newegstring = egstring.replace(/Sonia/gi,She);
/*Update the paragraph with new string*/
document.getElementById('egstring').innerHTML = Newegstring;
}
0 Comment(s)