Javascript - 替换文本中基于对象的值的最快、最有效的方法
我有一个看起来像这样的对象:
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)}}
替换为等效的 并检查它是否具有每个字符串的匹配值,但我确信有更好更快的方法来做到这一点。
有什么想法吗?
I have an object that looks like this:
var obj = {
a: "text",
b: "text 2",
c: "text 3",
...
}
and I have a bunch of strings that look like this:
var stringA = "http://{{a}}.something.com/",
stringB = "http://something.{{b}}.com/",
stringC = "http://something.com/{{c}}";
I want to replace {{(\w)}}
with it's equivalent by going through obj
and checking if it has my matched value for every string, but I'm sure there is a better and faster way to do so.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Douglas Crockford 编写了一个名为
supplant
的函数,它几乎完全可以满足您的需求。我稍微改变了函数以匹配您的双花括号 -演示 - http://jsfiddle.net/saZGg/
Douglas Crockford wrote a function called
supplant
that does almost exactly what you want. I've altered the function slightly to match your double curly braces -Demo - http://jsfiddle.net/saZGg/
或者使用
.replace
解决方案之一,这无疑更优雅。Or use one of the
.replace
solutions which is arguebly more elegant.应该这样做:
它只是查找对象是否具有具有捕获名称的属性。如果没有,则不会替换任何内容。
用法:
This should do it:
It just looks up whether the object has a property with the captured name. If not, nothing is replaced.
Usage: