javascript将方法参数插入字符串模板

发布于 2024-12-04 14:21:40 字数 644 浏览 0 评论 0原文

我不确定最终的实现具体如何,但基础知识是将方法参数插入到字符串“模板”中。第一种情况,我可以只进行正则表达式替换,但这有一些缺点,如果有必要,我愿意接受。第二个有点困难。如何从模板中获取名称并替换为传递对象中的匹配名称?感谢您的任何帮助。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

日久见人心 2024-12-11 14:21:40

如果您不需要额外的检查和验证,您只需将 {key} 替换为 value 即可,例如:

function applyTemplate(tpl,o) {
    for(var key in o)
        {
            if(o.hasOwnProperty(key))// prevent iteration on any prototype inherited methods
                tpl = tpl.replace('{'+key+'}',o[key]);
        }
    return tpl;
}

至于您简单的第一个 applyTemplate 函数,因为您对键应该是什么没有任何概念,所以您可以使用正则表达式仅替换遇到的第一个 {...}

 function applyTemplate(tpl,str) {
     return tpl.replace(/{.*?}/,str);
}

然后,当然,您可以将这些组合起来两个功能合而为一,略有不同基于参数类型的功能:

 function applyTemplate(tpl,o) {
    switch(typeof o){
        case 'object' : 
            for(var key in o)
                {
                    if(o.hasOwnProperty(key))
                        tpl = tpl.replace('{'+key+'}',o[key]);
                }
            break;
        case 'string' : 
           tpl = tpl.replace(/{.*?}/,o);
           break;
        default : 
            throw new Error('no valid parameters supplied');
    }
    return tpl;
}

这应该可以解决问题。如果您有兴趣,您可以了解一下 jquery 模板系统:http://api.jquery。 com/jQuery.template/

希望这有帮助。

If you don't need extra checking&validation, you could just replace the {key} with the value such as :

function applyTemplate(tpl,o) {
    for(var key in o)
        {
            if(o.hasOwnProperty(key))// prevent iteration on any prototype inherited methods
                tpl = tpl.replace('{'+key+'}',o[key]);
        }
    return tpl;
}

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 :

 function applyTemplate(tpl,str) {
     return tpl.replace(/{.*?}/,str);
}

And then, of course , you can combine these two functions in one, with slightly different functionalities based on the type of the arguments:

 function applyTemplate(tpl,o) {
    switch(typeof o){
        case 'object' : 
            for(var key in o)
                {
                    if(o.hasOwnProperty(key))
                        tpl = tpl.replace('{'+key+'}',o[key]);
                }
            break;
        case 'string' : 
           tpl = tpl.replace(/{.*?}/,o);
           break;
        default : 
            throw new Error('no valid parameters supplied');
    }
    return tpl;
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文