我正在尝试使用replace()方法将我的字符串中的'parameters'替换为参数的实际值,但由于某种原因,我无法让它工作。我正在使用的字符串是:
var temp = "This {{application}} will be down from {{start}} to {{finish}}."
我想用应用程序名称替换{{application}},依此类推。
var regEx = /{{(.*?)}}/;
这是我用来获取括号和该部分之间的值的正则表达式。这是我的其余代码:
if (regEx.exec(temp)[1] === "application") {
temp.replace(regEx, params.value);
}
'params.value'是应用程序的名称。我认为这会奏效,但事实并非如此。
答案 0 :(得分:1)
仅替换单个字符串(静态)
var appName = "application"; // String to replace
var regex = new RegExp("{{" + appName + "}}", "g"); // Use `g` flag to replace all occurrences of `{{application}}`
temp = temp.replace(regex, param.value);
var appName = "application",
regex = new RegExp("{{" + appName + "}}", "g"),
temp = "This {{application}} will be down from {{start}} to {{finish}}.";
var param = {
value: 'StackOverflow'
};
temp = temp.replace(regex, param.value);
console.log(temp);
document.body.innerHTML = temp;

将括号内的所有字符串替换为各自的值(动态)
您可以将String#replace
与对象一起使用来替换值。
var regex = /{{(.*?)}}/g;
// Match all the strings in the `{{` and `}}`
// And put the value without brackets in captured group
temp = temp.replace(regex, function(m, firstGroup) {
// m: Complete string i.e. `{{foobar}}`
// firstGroup: The string inside the brackets
return params[firstGroup] || 'Value not found in params';
// If the value for the key exists in the `params` object
// replace the string by that value
// else
// replace by some default string
});
var params = {
application: 'Stack Overflow',
start: 'On Sunrise',
finish: 'In Dreams'
};
var temp = "This {{application}} will be down from {{start}} to {{finish}}.";
var regex = /{{(.*?)}}/g;
temp = temp.replace(regex, function(m, firstGroup) {
return params[firstGroup] || 'Value not found in params';
});
console.log(temp);
document.body.innerHTML = temp;

答案 1 :(得分:1)
这是一个帮助函数来产生你期望的
function replace(str, dict) {
return str.replace(/{{(.*?)}}/g, function(match, $1) {
return dict[$1] || match;
});
}
replace(
"This {{application}} will be down from {{start}} to {{finish}}.",
{
'application': 'pigeon',
'start': '8am',
'finish': '9pm'
}
);
// "This pigeon will be down from 8am to 9pm."
这将接受要替换和替换的值的映射。并返回格式正确的字符串。
答案 2 :(得分:0)
您可以在替换中使用回调来评估捕获组内容:
var name = "Google";
var temp = "This {{application}} will be down from {{start}} to {{finish}}.";
var res = temp.replace(/{{(.*?)}}/g, function (m, g) {
return g === "application" ? name : m;
});
document.body.innerHTML = res;
此处,m
是带有大括号的整个匹配文本,而g
是没有大括号的子匹配。