如何使用 REGEX 从 JavaScript 中的字符串中替换标记 [英] How to replace a token from the string in JavaScript using REGEX

查看:30
本文介绍了如何使用 REGEX 从 JavaScript 中的字符串中替换标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have such template "text %variable.key% text". The variable.key is the variable. And I need to rename such variables to "text "+variable.key+" text", to make them work.

我曾尝试做这样的事情:

I have tried to do something like this:

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

但它也返回一个字符串.

but it also returns a string.

有人能告诉我怎么做吗?

Can somebody tell me how to do this?

推荐答案

完全不用 eval 也很容易:

It's easy to do without using eval at all:

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;
}

如果你想从 window 开始获取属性,你可以调用 getValue("path.to.property").如果您想从其他根对象开始,请使用 getValue.call(rootObject, "path.to.property").

If you want to get properties starting from window you can just call getValue("path.to.property"). If you want to start from some other root object, use getValue.call(rootObject, "path.to.property").

该函数也可以采用根对象作为可选的第一个参数,但思想保持不变.

The function could also be adapted to take the root object as an optional first parameter, but the idea remains the same.

查看实际操作.

重要提示:这不适用于 Internet Explorer <9 因为 Array.prototype.forEach 将不存在.你可以用

Important: This will not work on Internet Explorer < 9 because Array.prototype.forEach will not exist. You can fix that with

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);
            }
        }
    };
}

这篇关于如何使用 REGEX 从 JavaScript 中的字符串中替换标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆