[英]Replace all occurrences of the dot character with an underscore character in javascript
[英]How to replace all words match after a specific character but by ignoring underscore in javascript?
假设我有一个名为target的字符串和一个名为 object 的数据,它们定义为:
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()]
})
你能帮助我吗?
您可以更新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));
我认为这将永远有效:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.