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 wan
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 `
`. Otherwise, return a empty string.
return replacements[key] !== undefined
? "
" + 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.