JavaScript替换-替换的动态价值 [英] Javascript Replace - Dynamic Value of Replacement

查看:38
本文介绍了JavaScript替换-替换的动态价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在字符串中有一个模板,我想用另一个字符串中的值替换一些占位符.对于我替换的每个占位符,我还想插入一个break标签.

I have a template in a String and I want to replace a few of the placeholders with the values that I have in another string. For every placeholder that I replace, I also want to insert a break tag.

例如,如果在模板中找到了#ADDRESS2#,则我使用以下代码将其所有出现的内容替换为字符串 val.address2 中的值.

For eg if #ADDRESS2# is found in the template, I am using the following code to replace all its occurrences with value in string val.address2.

    template_html = template_html.replace(/#ADDRESS2#/g, '<br />'+ val.address_2);

但是,在某些情况下,字符串 val.address2 为空.在这种情况下,我不想插入break标签.

However there are scenarios when the string val.address2 is empty. In that case, I do not want to insert the break tag.

所以我如下更改了代码

    if( val.address_2.length > 0 ) {
        template_html = template_html.replace(/#ADDRESS2#/g, '<br />'+ val.address_2);
    } else {
        template_html = template_html.replace(/#ADDRESS2#/g, '');
    }

是否有更好的方法编写上述代码,因为我有多个占位符,对于每个占位符,我必须编写两次代码.

Is there a better way to write the above code as I have multiple Placeholders and for each Placeholder I have to write the code 2 times.

推荐答案

使用正则表达式替换,您将函数传递给该替换.

Use a regex replacement, to which you pass a function.

该函数将获取替换键作为输入,并且根据是否有替换键,它将插入一个空字符串或带换行符的替换键:

That function will get the replacement keys as input, and depending on if there's a replacement available, it will insert a empty string, or the replacement with a linebreak:

const template = "#foo# this bla bla #bar# but #baz# and stuff";

const replacements = {
  foo: "test",
  bar: "",
  baz: "not empty"
};

const result = template.replace(/#([^#]+)#/g, (match, key) => {
  // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
  return replacements[key] !== undefined
    ? "<br />" + replacements[key]
    : "";
});

console.log("template:", template);
console.log("result:", result);

这里唯一的陷阱"是模板字符串中的键必须与替换对象中的键匹配.不过,这不一定是一件坏事,因为如果您稍后再看一下代码,它将使它更加直观.

The only "gotcha" here is that the keys in the template string have to match the keys in your replacements object. That's not necessarily a bad thing, though, as it would make it slightly more intuitive if you'd look back at your code later on.

正则表达式可能看起来很吓人,但这确实非常简单:

The regex may look intimidating, but it's really quite simple:

/#([[^#] +)#/g

  • /:正则表达式的开始,
  • #:字面上是#字符,
  • (:捕获组的开始,
  • [^#] + 不是#的任何字符. + 确保它与尽可能多的匹配,
  • ):捕获组的结尾,
  • #:字面上是#字符,
  • /g :正则表达式的结尾. g 是全局标志,因此它不会在第一个结果处停止.
  • /: The start of the regex,
  • #: Literally the # character,
  • (: The start of a capturing group,
  • [^#]+ Any character that isn't a #. The + makes sure it matches as many as possible,
  • ): The end of a capturing group,
  • #: Literally the # character,
  • /g: The end of the regex. g is the global flag, so it doesn't stop at the first result.

捕获组基本上告诉正则表达式将括号之间的所有内容归为一组.然后分别返回组.

The capturing group basically tells the regex to group everything that's between the brackets. The groups are then returned individually.

这篇关于JavaScript替换-替换的动态价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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