jQuery/Javascript solution for replacing multiple abbreviations

霸气de小男生 提交于 2021-02-04 19:30:06

问题


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


回答1:


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.




回答2:


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.


来源:https://stackoverflow.com/questions/37299925/jquery-javascript-solution-for-replacing-multiple-abbreviations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!