String.replace() is a very common method that most of us would have used. Let us take a look at it.
The syntax of String.replace() is :
/* where 'string' is your string object or a string */ 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.
Let’s 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 :
The Answer !!
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 we can replace all string or text 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. */
str = str.replace(‘/John/gi’,’He’);
Please remove ‘ from that code
ans :- str = str.replace(/John/gi,’He’);
Thanks for pointing that out Mayank. We’ve updated it.
Fred this would not work out as its not case sensitive too. However to support your point, yes you can also extend the existing String object’s replaceAll method. But then remember that we need to be careful always before we extend any pre-defined objects.
Comments are closed.