Home > Net >  Using maps over template literals
Using maps over template literals

Time:04-14

so I need to print a boolean value if the given string contains [[placeholder:var3]] but the var3 will be dynamically fed from an array as belwo:

 variabless=["var1","var2","var3"]

 let s="I like [[placeholder:var3]]";

 console.log(s.includes(`[[placeholder:${variabless}]]`));

I tried using map around the template literals but it is throwing me an error also tried like above eg but it checks only first value of the array, so can someone please help me solve this, I'd appreciate any help, thanks in advance.

CodePudding user response:

You need to tell the index inside template literals becasue variabless is an array like this:

console.log(s.includes(`[[placeholder:${variabless[2]}]]`));

I hope it helps you.

CodePudding user response:

you're currently passing the whole array in s.includes([[placeholder:${variabless}]]), and that's won't work, you need to specify which elemnt of the variables array you want to inject to your string which is element indexed with 2 so it should be like that s.includes([[placeholder:${variabless[2]}]])

CodePudding user response:

To match against any value in variabless, you can test against a regular expression:

console.log(new RegExp(
   `\\[\\[placeholder:(${variabless.join('|')})\\]\\]`
 ).test(s));

CodePudding user response:

[[placeholder:${variabless}]] yields [[placeholder:var1,var2,var3]]. It doesn't check the first variable. And that's not how Array.string.includes is supposed to be used. For checking exact match use the === operator.

In case you want to check if any of the array elements match the string you can use the Array.prototype.some method which returns a boolean value.

let any = variabless.some(el => s === `[[placeholder:${el}]]`)

If you want to find the element that matches with the string use the Array.prototype.find function.

  • Related