[英]What is the quickest/most efficient way to find the first occurrence index of an object in an list with javascript?
[英]Javascript - The quickest and most efficient way to replace object-based values in text
我有一个看起来像这样的对象:
var obj = {
a: "text",
b: "text 2",
c: "text 3",
...
}
我有一堆看起来像这样的字符串:
var stringA = "http://{{a}}.something.com/",
stringB = "http://something.{{b}}.com/",
stringC = "http://something.com/{{c}}";
我想通过遍历obj
并检查它是否具有每个字符串的匹配值来替换{{(\\w)}}
以使其等效,但是我敢肯定有一种更好,更快的方法。
有任何想法吗?
道格拉斯Crockford的写了一个函数调用supplant
,做几乎正是你想要的。 我对功能做了些微修改,以匹配您的双花括号-
if (typeof String.prototype.supplant !== 'function') {
String.prototype.supplant = function (o) {
return this.replace(/{{([^{}]*)}}/g, function (a, b) {
var r = o[b];
return typeof r === 'string' ? r : a;
});
};
}
var obj = {
a: "text",
b: "text 2",
c: "text 3"
}
var stringA = "http://{{a}}.something.com/",
stringB = "http://something.{{b}}.com/",
stringC = "http://something.com/{{c}}";
alert(stringA.supplant(obj));
var arr = /(.*){{(\w)}}(.*)/.exec(stringA);
arr[2] = obj[arr[2]];
arr.shift(); // remove full string at start
var newString = arr.join("");
或者使用.replace
解决方案之一,该解决方案显然更优雅。
应该这样做:
function format(str, values) {
return str.replace(/{{(\w)}}/g, function(match, name) {
return values[name] || match;
});
}
它只是查询对象是否具有带有捕获名称的属性。 如果没有,则什么也不会取代。
用法:
var str = format(stringA, obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.