gpt4 book ai didi

javascript - 使用 RegEx 替换字符串的一部分 - Javascript

转载 作者:行者123 更新时间:2023-12-02 15:05:20 26 4
gpt4 key购买 nike

我试图使用replace()方法将字符串中的“参数”替换为参数的实际值,但由于某种原因我无法让它工作。我使用的字符串是:

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”是应用程序的名称。我以为这会起作用,但事实并非如此。

最佳答案

仅替换单个字符串(静态)

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;

关于javascript - 使用 RegEx 替换字符串的一部分 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35154910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com