简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM