Javascript - 将值匹配(并替换)到数组的数组

标签 javascript replace match

通过 Ajax 请求 (GET) 解析值后,我需要将它们替换为其他值 -> 即对应于同一国家代码的多个邮政编码(“1991,1282,6456”:“Idaho”等)

这是我到目前为止所做的:

$mapCodes = {
  '1991': 'Idaho',
  '1282': 'Idaho',
  '5555': 'Kentucky',
  '7777': 'Kentucky '
}
var region = value.groupid.replace(/7777|5555|1282|1991/, function(matched) {
  return $mapCodes[matched];
});
console.log(region);

这可行,但我宁愿避免将我的 $mapCodes 变量设置为一长串重复的值。

我需要类似的东西和数组的数组来匹配(然后替换)

$mapCodes = {
'1991,1282' : 'Idaho',
'7777,5555' : 'Kentycky'
}

最佳答案

您需要使用数组,其中元素是 $mapCodes 的键:

{
  "Idaho":[1991,1282]
}

这是演示:

$mapCodes = {
  "Idaho":['1991','1282'],
  "Kentucky":['5555','7777']
}
var test="1991 7777 1282";  /// input string
var region = test; // result string
for(let key in $mapCodes){
  let a =$mapCodes[key];
  for(let i=0; i<a.length; i++) {
    region = region.replace(a[i],key);
  }
}
console.log(region);

关于Javascript - 将值匹配(并替换)到数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865426/

相关文章:

regex - Powershell - 如何用字符串中的变量替换数字?

jquery - 定位精确文本匹配 (jQuery)

javascript - AngularJS 范围在 1.0.x 和 1.2.x 之间的差异

javascript - 如何在 ASP.NET MVC 中将数据从 React 发送到 Controller?

Javascript 正则表达式建议

c - 使用 C 替换文件中的单词

javascript - 如何解析存储在数组中的数据

java - 用 Java 中的 RegEx 替换除一个之外的所有标签

javascript - 正则表达式匹配开始使用变量

删除在 R 中开始和结束处包含句点的行