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

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

Replace all variables in string using RegEx

问题

  1. var str = "The {type} went to the {place}";
  2. var mapObj = {
  3. type: 'Man',
  4. place: 'Shop'
  5. };
  6. var re = new RegExp(/(?<=\{)Object.keys(mapObj).join("|")(?=\})/, "gim");
  7. str = str.replace(re, function(matched){
  8. return mapObj[matched.toLowerCase()];
  9. });
  10. 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

  1. var str = &quot;The {type} went to the {place}&quot;;
  2. var mapObj = {
  3. type: &#39;Man&#39;,
  4. place: &quot;Shop&quot;
  5. };
  6. var re = new RegExp(/(?&lt;=\{)Object.keys(mapObj).join(&quot;|&quot;)(?=\})/, &quot;gim&quot;);
  7. str = str.replace(re, function(matched){
  8. return mapObj[matched.toLowerCase()];
  9. });
  10. 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

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

  1. var str = "The {type} went to the {place}";
  2. var mapObj = {
  3. type: 'Man',
  4. place: "Shop"
  5. };
  6. str = str.replace(/\{([^{}]+)\}/gim, function(_, c) {
  7. return mapObj[c.toLowerCase()] || `{${c}}`;
  8. });
  9. 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 -->

  1. var str = &quot;The {type} went to the {place}&quot;;
  2. var mapObj = {
  3. type: &#39;Man&#39;,
  4. place: &quot;Shop&quot;
  5. };
  6. str = str.replace(/\{([^{}]+)\}/gim, function(_, c) {
  7. return mapObj[c.toLowerCase()] || `{${c}}`;
  8. });
  9. 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:

确定