String.replace() is a very common method that most of us would have used. Lets take a look at it.
The syntax of String.replace() is :
//where 'string' is your string object string.replace(searchvalue,newvalue);
In the syntax above, the “string” refers to the String object that you want to execute the “replace” method on, “searchvalue” refers to the word / character that you want to look for and replace within the string, and the “newvalue” refers to the new word/character that you want to replace the “searchvalue” with.
Lets look at an example of the Default behaviour :
var str = "John is happy today as john won the match today"; // Let's replace "John" with "He". //However, Please note that this is the default behavior and not the actual solution! str = str.replace('John','He'); // str becomes: // He is happy today as john won the match today.
However, if you notice the second occurrence of “john” was not replaced. That is exactly what the replace method does. It by default replaces only the first occurrence of the string to be replaced or the search string.
string.replace() method, you’ll have to pass the search string as a regular expression. For example :
var str = "John is happy today as john won the match today. John made 100 runs."; // Let's replace "John" with "He". str = str.replace(/John/g,'He'); // str becomes: // He is happy today as john won the match today. He made 100 runs. // To make the search case-insensitive pass the "i" parameter // in regular expression. str = str.replace(/John/gi,'He'); //Now str becomes : // He is happy today as He won the match today. He made 100 runs.
Also since the search is case sensitive, we had to pass the “i” parameter in the regular expression along with the “g” parameter to make the search case-insensitive. You may consider reading more about regular expressions, they are extremely useful.
jQuery string replace all
Even in jQuery replace all string or replace text in jQuery or a replaceall jquery can be done using the same method. All you need to do is to access the string value using one of the jQuery Selectors and run it through the regex mentioned in the example above.
Typescript Replace all occurrences of a string
let myStr = "John is happy today as john won the match today. John made 100 runs."; myStr = myStr.replace(/John/gi, 'Tom'); //makes myStr as "Tom is happy today as Tom won the match today. Tom made 100 runs.