Replacing one occurance
In this example, I'll show you how to use the "replace" function to replace one occurance of a string in a string:
var str = "This is a string"; var result = str.replace("string", "sentence"); console.log(result);
If you run this code in your browser, you will see this sentence in your console log: "This is a sentence". So the first value you pass in is the word you search for, and the second value you pass in is the value you want to replace it with.
If you change the value of the "str" variable to this "This is a string and more string", it will still only replace the first occurance.
Replacing all occurances
Almost all of the times, you want to replace all of the occurances of a word in a string. To do this, we need to perform a global replacement using regular expressions. This isn't as hard as it sounds. Let me show you an example:
var str = "This is a string with more than one string."; var result = str.replace(/string/g, "sentence"); console.log(result);
If you run this in your browser, the console log will say "This is a sentence with more than one sentence."
The global replace is case sensitive, so you need to modify the expression above if you want to replace both lowercase and uppercase occurances. The only thing you need to do, is to replace the "g" after the "/" with "gi". That means that it's global and insensitive.