【问题标题】:Replace all variables in string using RegEx使用 RegEx 替换字符串中的所有变量
【发布时间】:2020-01-03 17:59:10
【问题描述】:

结合以前的几个答案,我试图组合一个正则表达式,它可以让我替换大括号内所有出现的任何东西

我已经走了这么远,但它似乎不起作用

var str = "The {type} went to the {place}";


var mapObj = {
   type: 'Man',
   place: "Shop"

};
var re = new RegExp(/(?<=\{)Object.keys(mapObj).join("|")(?=\})/, "gim");
str = str.replace(re, function(matched){
  return mapObj[matched.toLowerCase()];
});

console.log(str);

我在上一个答案中添加了 (?

上一个答案 - Replace multiple strings with multiple other strings

【问题讨论】:

  • 我会尝试简单地 /\{([^}]+)\}/ 匹配任何被花括号包围的字符串。

标签: javascript regex


【解决方案1】:

使用捕获组,您将获得作为替换回调的第二个参数的值:

var str = "The {type} went to the {place}";

var mapObj = {
  type: 'Man',
  place: "Shop"

};

str = str.replace(/\{([^{}]+)\}/gim, function(_, c) {
  return mapObj[c.toLowerCase()] || `{${c}}`;
});

console.log(str);

【讨论】:

  • 鉴于 OP 问题的性质,我想在某些情况下字符串中的变量在 mapObj 中不匹配。
  • return mapObj[c.toLowerCase()] !== undefined ? mapObj[c.toLowerCase()] : '{'+c+'}'; 这样的东西可以解决它。
  • 效果很好,添加了@MonkeyZeus 的建议,因为可能存在变量与 mapObj 中的键不匹配的情况,因此最好按原样返回它
  • @TamoorMalik 我建议使用我评论中的return 语句,因为它可以正确处理不匹配的数据类型,以便您可以可靠地执行type: 0 之类的操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
  • 2014-04-19
  • 1970-01-01
  • 2013-07-23
  • 2011-08-30
  • 2019-04-30
  • 2020-07-09
相关资源
最近更新 更多