简体   繁体   中英

jQuery/Javascript solution for replacing multiple abbreviations

For example I need something that will parse a string and go through and replace multiple street types abbreviations with their full word ('Rd' would become 'Road'). This is sort of answered here but I would like something with a single object like below because this is going to be a pretty long list and this would help keep the correct organization,

var streets = {
       'RD': 'ROAD',
       'ST': 'STREET',
       'PL': 'PLACE'};

I know I've seen things like this before, but I'm kind of lost as to how to proceed from here. I know I need to take the string in question and run the value through this 'filter' (if you can call it that), but I'm just not sure how since I'm still pretty new to this. Thanks so much

You would just need a simple for/in loop to iterate through the keys and replace them in the string, something like this:

 var input = "something RD, other ST, some PL, another RD"; var streets = { 'RD': 'ROAD', 'ST': 'STREET', 'PL': 'PLACE' }; for (var key in streets) { var re = new RegExp(key, 'gi'); input = input.replace(re, streets[key]); } console.log(input); 

You could also change the regular expression logic to make the match more accurate if required; it would depend entirely on the format of your input string.

For fixed strings, use .split().join() like this

var streets = { 'RD': 'ROAD', 'ST': 'STREET', 'PL': 'PLACE'};
var str = 'Some ST that is by the PL along the RD where the ST is by that PL.'

for(k in streets){ str = str.split(k).join(streets[k]) }

Result

console.log(str)
Some STREET that is by the PLACE along the ROAD where the STREET is by that PLACE.

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