Javascript正则表达式用新单词替换多个单词 [英] Javascript regex to replace multiple words with new words

查看:125
本文介绍了Javascript正则表达式用新单词替换多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次渲染HTML模板时,我都试图用新词替换多个词.

I'm trying to replace multiple words with new words, each time I'm rendering an HTML template.

我不必
遍历模板(这相当大)来查找三个不同的单词,而是想组合这三个单词和它们的替换,而不必遍历整个模板模板一次. (此外,显然,下面的代码仅替换了最后一个单词{id},因为它会覆盖上面的其他两个替换尝试.)

Instead of having to loop through the template (which is quite big) three times to look for three different words, I'd like to combine the three words and their replacements, and only loop through the template once. (Also, obviously below code only replaces the last word, {id} since it overrides the other two replacement attempts above it).

       $.get('/templates/list-item.html', function(data) {
          var template = data,
              tmp = '';

          $.getJSON('conf.json', function(data) {
            var items = [],
                list = data.default;

            for (var item in list) {
              var name = item.name,
                  value = list[item].value,
                  id = list[item].id;

              tmp = template.replace('{name}', name);
              tmp = template.replace('{value}', value);
              tmp = template.replace('{id}', id);

              items.push(tmp);
            }

            $('<div/>', {
              html: items.join('')
            }).appendTo('body');
          });
        });

显然,渲染模板不应该使用JS完成,但是由于它仅供内部使用,因此没有可用的后端,并且不需要Google对其进行索引,暂时还可以.

Obviously rendering templates shouldn't be done with JS, but since it's for internal use only, no backend is available and it doesn't need to be indexed by Google, it's fine for the time being.

推荐答案

您可以使用回调函数来替换模板变量.考虑例如:

You can use a callback function to replace template variables. Consider for example:

template = "{foo} and {bar}"
data = {foo:123, bar:456}

template.replace(/{(\w+)}/g, function($0, $1) {
    return data[$1];
});

我还建议将循环替换为 map():

I'd also suggest replacing the loop with map():

items = $.map(list, function(item) {
   var data = {name: item.name, value:.... etc }
   return template.replace(/{(\w+)}/g, function($0, $1) {
       return data[$1];
   });
}

/{(\w+)}/g的基本含义是:

/                - start pattern
{                - match { literally
    (            - begin group 1
        \w       - a "word" character (letter+digit+underscore)
        +        - repeat once or more
    )            - end group 1
}                - match } literally
/                - end pattern
g                - match globally, i.e. all occurences

调用回调函数时,它将整个匹配项作为第一个参数,将组1的值作为第二个参数.因此,当看到{foobar}时,它将调用callback("{foobar}", "foobar").

When the callback function is called, it gets the whole match as its first parameter and the value of the group 1 as the second. So when it sees {foobar}, it calls callback("{foobar}", "foobar").

这篇关于Javascript正则表达式用新单词替换多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆