In JavaScript, there are several ways to replace all occurrences of a string within a larger string. One common method is to use the replace()
function, which allows you to search for a specific string and replace it with another string.
Here is an example of using the replace()
function to replace all occurrences of the word “old” with the word “new”:
let str = "This is my old car. I want to buy a new car.";
let newStr = str.replace(/old/g, "new");
console.log(newStr); // "This is my new car. I want to buy a new car."
In the example above, the replace()
function takes two arguments: the first is a regular expression that matches the string you want to replace (in this case, “old”), and the second is the string you want to replace it with (in this case, “new”). The g
flag is used to specify that all occurrences should be replaced, rather than just the first one.
Another method of replacing all occurrences of a string is to use the split()
and join()
functions. The split()
function is used to split a string into an array of substrings, and the join()
function is used to join the array back into a string. Here is an example of using split()
and join()
to replace all occurrences of the word “old” with the word “new”:
let str = "This is my old car. I want to buy a new car.";
let newStr = str.split("old").join("new");
console.log(newStr); // "This is my new car. I want to buy a new car."
In the example above, the split()
function splits the original string into an array of substrings, each of which is delimited by the word “old”. The join()
function then joins the array back into a string, replacing each occurrence of “old” with “new”.
There are other ways to replace all occurrences of a string in JavaScript, like using for
loops, but the above mentioned methods are some of the most common.
It’s important to note that replace()
function doesn’t change the original string, it only returns a new one with the replaced string. In case you want to change the original string you could use the assignment operator:
str = str.replace(/old/g, "new");
Also, it’s important to note that the regular expression used in the replace()
function should be used carefully as it could replace unintended parts of the string, so be sure to use the correct regular expressions.