Javascript Replace - Dynamic Value of Replacement

2020-04-10 02:57发布

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.

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);

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

So I changed my code as follows

    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.

标签: javascript
7条回答
相关推荐>>
2楼-- · 2020-04-10 03:41

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

  • /: 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.

查看更多
登录 后发表回答