javascript将方法参数插入字符串模板
我不确定最终的实现具体如何,但基础知识是将方法参数插入到字符串“模板”中。第一种情况,我可以只进行正则表达式替换,但这有一些缺点,如果有必要,我愿意接受。第二个有点困难。如何从模板中获取名称并替换为传递对象中的匹配名称?感谢您的任何帮助。
var myTemplate = 'Hello {name}'; // or something similar
var name = 'Bob';
function applyTemplate(tpl,str) {
//do stuff here to replace {name} with passed argument
}
var newStr = applyTemplate(myTemplate,name); //should return 'Hello Bob'
//Also this one
var myTemplate = 'Good {timeOfDay} {name}';
function applyTemplate(tpl,o) {
//simple objects only, don't need nested
}
var newStr = applyTemplate(myTemplate,{name:'Bob',timeOfDay:'morning'}); //should return 'Good morning Bob'
I'm not sure exactly how the final implementation will be, but the basics are to insert method arguments into a string "template". The first instance, I could just do a regex replace but that has some downfalls, which I'm willing to accept if necessary. The second one is a bit more difficult. How can I get the names from the template and replace with matched from the passed object? Thanks for any help.
var myTemplate = 'Hello {name}'; // or something similar
var name = 'Bob';
function applyTemplate(tpl,str) {
//do stuff here to replace {name} with passed argument
}
var newStr = applyTemplate(myTemplate,name); //should return 'Hello Bob'
//Also this one
var myTemplate = 'Good {timeOfDay} {name}';
function applyTemplate(tpl,o) {
//simple objects only, don't need nested
}
var newStr = applyTemplate(myTemplate,{name:'Bob',timeOfDay:'morning'}); //should return 'Good morning Bob'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不需要额外的检查和验证,您只需将
{key}
替换为value
即可,例如:至于您简单的第一个
applyTemplate 函数,因为您对键应该是什么没有任何概念,所以您可以使用正则表达式仅替换遇到的第一个
{...}
:然后,当然,您可以将这些组合起来两个功能合而为一,略有不同基于参数类型的功能:
这应该可以解决问题。如果您有兴趣,您可以了解一下 jquery 模板系统:http://api.jquery。 com/jQuery.template/。
希望这有帮助。
If you don't need extra checking&validation, you could just replace the
{key}
with thevalue
such as :As for your simple first
applyTemplate
function, since you do not have any notion about what the key should be, you can use regex to replaceonly the first{...}
encountered :And then, of course , you can combine these two functions in one, with slightly different functionalities based on the type of the arguments:
This should do the trick. If you are interested, you could take a peak at the jquery template system : http://api.jquery.com/jQuery.template/.
Hope this helped.