Learn the proper way to replace all occurrences of a string in plain JavaScript, including using regular expressions and other approaches.

Using a Regular Expression

To replace all occurrences of a string with another string, you can use a regular expression. This simple regex, String.replace(/<TERM>/g, ''), will perform the task. Note that it is case sensitive.

Here’s an example that demonstrates replacing all occurrences of the word “dog” in the string phrase:

const phrase = 'I love my dog! Dogs are great';
const stripped = phrase.replace(/dog/g, '');

console.log(stripped); // Output: "I love my ! Dogs are great"

If you want to perform a case-insensitive replacement, you can modify the regular expression to include the i option: String.replace(/<TERM>/gi, '').

Here’s an example that shows replacing all occurrences of the word “dog” in a case-insensitive manner:

const phrase = 'I love my dog! Dogs are great';
const stripped = phrase.replace(/dog/gi, '');

console.log(stripped); // Output: "I love my ! s are great"

If your string contains special characters, remember to escape it using the escapeRegExp function. This function escapes special characters in a string and allows for proper pattern matching. Here is the escapeRegExp function:

const escapeRegExp = (string) => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

Using Split and Join

Another approach to replace all occurrences of a string is to use the split() and join() functions in JavaScript.

The split() function splits a string into an array of tokens based on a specified pattern (case sensitive). You can then use the join() function to join the tokens into a new string without any separator.

Here’s an example that demonstrates this approach:

const phrase = 'I love my dog! Dogs are great';
const tokens = phrase.split('dog');
const stripped = tokens.join('');

console.log(stripped); // Output: "I love my ! Dogs are great"

In conclusion, you now know how to replace all occurrences of a string in JavaScript. Whether you choose to use regular expressions or the split() and join() functions, you have options for achieving your desired result.