【问题标题】:How to replace all words match after a specific character but by ignoring underscore in javascript?如何替换特定字符后的所有单词匹配但忽略javascript中的下划线?
【发布时间】:2020-05-03 06:37:06
【问题描述】:

假设我有一个名为 target 的字符串和一个名为 data 的对象,它们被定义为:

var data : {
 value_1: "Hi"
}

var target = "Replace $value_1"

所以,要将 value_1 替换为 data 中设置的值,我这样做了:

target = target.replace(/\$(\w+)/gm, function(_, a) {
  console.log(a) // => value 
  // But I want value_1, I know "_" is not a word but how do I do it ?
  return data[a.trim()]
 })

你能帮帮我吗?

【问题讨论】:

  • 您的代码运行良好。这里有什么问题?

标签: javascript string object replace


【解决方案1】:

您可以更新regex 以匹配单词与num。

var data = {
  value_1: "Hi",
  value_2: "how",
  value_3: "are",
  value_4: "you",
};

var target = "Replace $value_1 $value_2 $value_3 $value_4?";
const template = (str) => str.replace(/\$(\w+_\d+)/g, (_, m) => data[m]);
console.log(template(target));

您可以使用string literal 来更好地处理和清洁代码。

示例:

function template(strings, ...keys) {
  return (dict) =>
    keys
      .reduce(
        (m, key, i) => {
          m = m.concat(dict[key], strings[i + 1]);
          return m;
        },
        [strings[0]]
      )
      .join("");
}
const dict = {
  value_1: "Hi",
  value_2: "how",
  value_3: "are",
  value_4: "you",
};

let html = template`Replace ${"value_1"} ${"value_2"} ${"value_3"} ${"value_4"}?`;
console.log(html(dict));

【讨论】:

    【解决方案2】:

    我认为这将永远有效:

    var data = {
     value_1: "Hi"
    }
    
    var target = "Replace $value_1";
    
    target = target.replace(/\$((\w|\_)+)/gm, function(_, a) {
      console.log(a) // => value 
      // But I want value_1, I know "_" is not a word but how do I do it ?
      return data[a.trim()]
     });
    
    console.log(target);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2020-05-08
      • 1970-01-01
      • 2017-12-08
      相关资源
      最近更新 更多