使用正则表达式替换字符串中的所有变量

huangapple go评论74阅读模式
英文:

Replace all variables in string using RegEx

问题

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);
英文:

Using a combination of a couple of previous answers I've tried to put together a RegEx that'll allow me to replace all occurrences of anything within curly braces

I got this far, but it doesn't seem to work

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


var mapObj = {
   type: &#39;Man&#39;,
   place: &quot;Shop&quot;

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

console.log(str);

I added (?<={) and (?=}) to the previous answer to have it only match occurrences where the key was within curly braces

Previous Answer - https://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings

答案1

得分: 3

使用捕获组,您将在替换回调的第二个参数中获取该值:

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);
英文:

Use a capture group, and you'll get the value as the 2nd param of the replace callback:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

var mapObj = {
  type: &#39;Man&#39;,
  place: &quot;Shop&quot;

};

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

console.log(str);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月4日 01:59:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/59583204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定