Replace All Occurrences Of A Substring In A String Javascript

Replace All Occurrences Of A Substring In A String Javascript

4 min read Jun 20, 2024
Replace All Occurrences Of A Substring In A String Javascript

Replace All Occurrences of a Substring in a String in JavaScript

In JavaScript, you can replace all occurrences of a substring within a string using the replace() method with a regular expression. This method allows you to search for a specific pattern and replace it with another string.

Here's how you can do it:

The replace() method with Regular Expressions

The replace() method takes two arguments:

  1. The pattern: This can be a string or a regular expression.
  2. The replacement string: This is the string that will replace the matched pattern.

To replace all occurrences, you need to use a regular expression with the global flag (g). This flag tells the replace() method to replace all matches, not just the first one.

Here is an example:

const originalString = "This is a string with many 'is' words.";
const newString = originalString.replace(/is/g, "was");
console.log(newString); // Output: This was a string with many 'was' words.

In this example, the regular expression /is/g searches for the substring "is" globally in the original string. The replace() method replaces all instances of "is" with "was", resulting in the new string: "This was a string with many 'was' words."

Using Case-Insensitive Matching

You can make the search case-insensitive by adding the i flag to the regular expression.

const originalString = "This is a String with many 'IS' words.";
const newString = originalString.replace(/is/gi, "was");
console.log(newString); // Output: This was a String with many 'was' words.

Now, the replace() method will find and replace both "is" and "IS" with "was".

Replacing with a Dynamic String

You can also replace the substring with a dynamic string, using a callback function as the second argument of the replace() method.

const originalString = "The quick brown fox jumps over the lazy fox.";
const newString = originalString.replace(/fox/g, (match) => {
  if (match === "fox") {
    return "dog";
  } else {
    return match;
  }
});
console.log(newString); // Output: The quick brown dog jumps over the lazy dog.

In this example, the callback function receives the matched string (match) as an argument. It checks if the match is "fox", and if so, replaces it with "dog". Otherwise, it returns the original match.

Conclusion

The replace() method with regular expressions is a powerful tool for manipulating strings in JavaScript. Using the global flag (g) and optional flags like i, you can replace all occurrences of a substring within a string, making your code more efficient and flexible.