Chirpizard
Chirpizard

Reputation: 291

String.replace for multiple unique characters and replacements

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.

Upvotes: 1

Views: 752

Answers (1)

Paul Roub
Paul Roub

Reputation: 36438

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);

Upvotes: 1

Related Questions