如何使用正则表达式替换JavaScript中字符串中的令牌

如何使用正则表达式替换JavaScript中字符串中的令牌,javascript,regex,string,replace,Javascript,Regex,String,Replace,我有这样的模板“text%variable.key%text”。variable.key是变量。 我需要将这些变量重命名为“text”+variable.key+“text”,以使它们工作 我尝试过这样做: var tpl = "text %variable.key% text"; tpl = tpl.replace(/%(.*?)%/, function(a,b) { return eval('b'); }); 但它也返回一个字符串 谁能告诉我怎么做 var tpl = "text

我有这样的模板“text%variable.key%text”。variable.key是变量。 我需要将这些变量重命名为“text”+variable.key+“text”,以使它们工作

我尝试过这样做:

var tpl = "text %variable.key% text";
tpl = tpl.replace(/%(.*?)%/, function(a,b) {
    return eval('b');
});
但它也返回一个字符串

谁能告诉我怎么做

var tpl = "text %variable.key% text";
tpl = tpl.replace(/%(.*?)%/, function(a,b) {
    return eval(b);// remove quote.
});


您的代码是正确的,但您需要评估
b
,而不是
'b'

var tpl = "text %variable.key% text";
tpl = tpl.replace(/%(.*?)%/, function(a,b) {
    return eval(b);
});
正如在评论中提到的,使用eval不是一种可行的方法。您也可以得到如下的变量值:

var tpl = "text %variable.key% text";
tpl = tpl.replace(/%(.*?)%/, function(a,b) {
    return window[b];
});

您的代码是正确的,但您需要评估
b
,而不是
'b'

var tpl = "text %variable.key% text";
tpl = tpl.replace(/%(.*?)%/, function(a,b) {
    return eval(b);
});
正如在评论中提到的,使用eval不是一种可行的方法。您也可以得到如下的变量值:

var tpl = "text %variable.key% text";
tpl = tpl.replace(/%(.*?)%/, function(a,b) {
    return window[b];
});

完全不用
eval
就可以轻松完成:

function getValue(path) {
    var target = this;
    path.split('.').forEach(function (branch) {
        if (typeof target === "undefined") return;
        target = (typeof target[branch] === "undefined") ? undefined : target[branch];
    });

    return target;
}
如果您想从
窗口
获取属性,只需调用
getValue(“path.to.property”)
。如果要从其他根对象开始,请使用
getValue.call(rootObject,“path.to.property”)

该函数也可以调整为将根对象作为可选的第一个参数,但其思想保持不变

重要提示:这在Internet Explorer<9上不起作用,因为
Array.prototype.forEach
将不存在。你可以用它来解决这个问题

if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fun /*, thisPointer */) {
        var len = this.length;
        if (typeof fun != "function") throw new TypeError();

        var thisPointer = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                fun.call(thisPointer, this[i], i, this);
            }
        }
    };
}
if(!Array.prototype.forEach){
Array.prototype.forEach=函数(fun/*,thisPointer*/){
var len=此长度;
如果(typeof fun!=“函数”)抛出新的TypeError();
var thisPointer=参数[1];
对于(变量i=0;i
完全不用
eval
就可以轻松完成:

function getValue(path) {
    var target = this;
    path.split('.').forEach(function (branch) {
        if (typeof target === "undefined") return;
        target = (typeof target[branch] === "undefined") ? undefined : target[branch];
    });

    return target;
}
如果您想从
窗口
获取属性,只需调用
getValue(“path.to.property”)
。如果要从其他根对象开始,请使用
getValue.call(rootObject,“path.to.property”)

该函数也可以调整为将根对象作为可选的第一个参数,但其思想保持不变

重要提示:这在Internet Explorer<9上不起作用,因为
Array.prototype.forEach
将不存在。你可以用它来解决这个问题

if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fun /*, thisPointer */) {
        var len = this.length;
        if (typeof fun != "function") throw new TypeError();

        var thisPointer = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                fun.call(thisPointer, this[i], i, this);
            }
        }
    };
}
if(!Array.prototype.forEach){
Array.prototype.forEach=函数(fun/*,thisPointer*/){
var len=此长度;
如果(typeof fun!=“函数”)抛出新的TypeError();
var thisPointer=参数[1];
对于(变量i=0;i
另一个不带eval()的变量适用于简单变量或对象:

var var_name = 'value';

// object
var obj = new Object();
 obj.prop = 'some val';

var tpl = "text %obj.prop% text %var_name% text";
tpl = tpl.replace(/%(.*?)%/gi, function(a,b) {
  var iv = b.split('.');
  return (iv.length == 2) ? window[iv[0]][iv[1]] : window[iv[0]];
});

// test
alert(tpl);

另一个变量不带eval(),可用于简单变量或对象:

var var_name = 'value';

// object
var obj = new Object();
 obj.prop = 'some val';

var tpl = "text %obj.prop% text %var_name% text";
tpl = tpl.replace(/%(.*?)%/gi, function(a,b) {
  var iv = b.split('.');
  return (iv.length == 2) ? window[iv[0]][iv[1]] : window[iv[0]];
});

// test
alert(tpl);

仅供参考,
eval
被强烈劝阻。除了
eval
的邪恶之外,我想除了Daniel White的评论之外,你还想使用
eval(b)
:尝试搜索
[js]eval-evil
,如果你想知道更多。谢谢你通知我。我不知道,仅供参考,
eval
被强烈劝阻。除了
eval
的邪恶之外,我想除了Daniel White的评论之外,你还想使用
eval(b)
:尝试搜索
[js]eval evil
,如果你想知道更多的话。谢谢你通知我。我不知道是的,这真的很有效。谢谢但是有没有其他的方法可以做同样的事情,但是不需要评估?是的,这确实有效。谢谢但是有没有其他的方法可以不做评估就做同样的事情呢?谢谢!我认为这是最好的解决方案!再次感谢你!只需为对象添加一点修复,谢谢!我认为这是最好的解决方案!再次感谢你!只需对对象进行一点修改就可以了毕竟,窗口有一个大痔疮[b]。所以我将使用你的解决方案。非常感谢。毕竟,有一个大痔疮的窗口[b]。所以我将使用你的解决方案。非常感谢。