如何使用 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);
}
}
};
}