Multiple Regex Replace Javascript

Multiple Regex Replace Javascript

3 min read Jun 20, 2024
Multiple Regex Replace Javascript

Multiple Regex Replace in JavaScript

Replacing multiple occurrences of patterns in a string is a common task in JavaScript. While you could chain multiple replace() calls, this can become cumbersome and inefficient for larger strings or complex patterns.

Luckily, JavaScript offers a more elegant solution: using a single replace() call with a regular expression and a replacement function.

How it Works

  1. Define your patterns: Create a regular expression that matches all the patterns you want to replace.
  2. Define your replacement function: Create a function that takes the matched string as an argument and returns the desired replacement.
  3. Apply replace(): Use the replace() method with your regular expression and replacement function.

Example: Replacing Multiple Vowels

Let's say you want to replace all vowels in a string with the letter 'x':

const string = "This is a test string.";

const vowelsRegex = /[aeiou]/gi; // Matches all vowels case-insensitive

const replacedString = string.replace(vowelsRegex, match => {
  return 'x';
});

console.log(replacedString); // Output: "Thxs xs x txst strxng."

In this example:

  • vowelsRegex matches all vowels (case-insensitive) using the gi flag for global and case-insensitive matching.
  • The replacement function simply returns 'x' for every matched vowel.

Advanced Usage: Dynamic Replacements

You can use the replacement function to perform more complex replacements, including:

  • Conditional replacements: You can use logic within the function to decide how to replace the matched string based on its content or other factors.
  • Dynamic replacements: You can dynamically generate the replacement string based on the matched value.
const string = "The price is $100.00 and the discount is $20.00";

const priceRegex = /\$[0-9]+(\.[0-9]{2})?/g; // Matches prices

const replacedString = string.replace(priceRegex, match => {
  const amount = parseFloat(match.substring(1));
  return `${(amount * 0.8).toFixed(2)}`; // Apply 20% discount
});

console.log(replacedString); // Output: "The price is $80.00 and the discount is $16.00"

Conclusion

By using a single replace() call with a regular expression and a replacement function, you can efficiently replace multiple occurrences of patterns in a string with dynamic and conditional logic. This makes your JavaScript code more concise and readable, while offering greater flexibility for complex replacements.