1

After reading MDN documentation, as well as W3schools, I'm still unsure of how to use .replace to replace multiple special characters all with their own unique replacement.

So if I write a function that takes a string as an argument, that string may be different each time, with special characters in each string. I want to be able to write a single replace statement that will check for those special characters and then depending up which special character is found, replace that character with a corresponding unique replacement.

An example, if I pass a string like dave & dave I may want to replace the & symbol with the characters "and" instead, which is simple enough, but what if the next string that is passed to the function has a $ that I want to replace with "dollar".

I can create such a function for a single unique character with replacement like:

string.replace(/&/g, "and");

But I'm not sure how to have multiple characters checked and then replaced with particular unique replacements.

Chirpizard
  • 291
  • 3
  • 17

1 Answers1

1

You could use a replacement function, something like:

var st = "& $ % !";

var replaced = st.replace(/[&$%!]/g, 
  function(piece) {
    var replacements = {
      "&": "and",
      "$": "dollar",
      "%": "pct",
      "!": "bang"
    };
  
    return replacements[piece] || piece;
  });

console.log(replaced);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • This does work! The only thing I don't understand is the `piece` argument passed into the function. How is the `piece`/symbol to be replaced get passed as the argument? Thanks for this solution, also! – Chirpizard Dec 01 '15 at 19:16
  • That's what `replace` *does* when you pass a function as the second argument. It passes each match to your function, and you return the replacement for that match. – Paul Roub Dec 01 '15 at 19:18
  • Awesome. Thanks for the explanation! – Chirpizard Dec 01 '15 at 19:22