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

标签 javascript regex

我试图使用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/

相关文章:

用于密码验证的 PHP 正则表达式

javascript - AngularJs $http.get : Sending array of objects as params

python - 追加到一行

javascript - Div 类未显示在下拉选择中?

javascript - Jquery click() 函数在单击链接时无法识别

ios - Swift 正则表达式查找全部

c# - 为什么这个词边界正则表达式不匹配

javascript - 为什么这个正则表达式输出不正确?

javascript - 如何获取所有 HTML 元素的 id?

javascript - ThreeJS轨迹球控制相机旋转