Home > Net >  How to check if a string includes a template literal in javascript?
How to check if a string includes a template literal in javascript?

Time:10-07

I have tried checking this using the function str.includes('${') as a trivial solution but I am not receiving the correct output. I am also getting back the strings that do not include it.

An example string that would satisfy this condition is: 'My name is ${customer.Name} '

CodePudding user response:

You can probably use Regex to find it. If you are just looking to see if a string just has a template literal in it you could do something like the following:

const str = 'My name is ${customer.Name} '

const regex = /\${(.*?)\}/g

const hasTemplateLiteral = (str) => str.search(regex) > -1

console.log(hasTemplateLiteral(str))

You can check the javascript regular expressions functions here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#using_regular_expressions_in_javascript. /\${(.*?)\}/g will check for the ${} with anything in between the brackets and return the index if it is found or return -1 if not found. You can test the regex here https://regexr.com/

Note this will only work if the template literal is actually in string format like your example above. If your template literal is in backticks then it will actually contain the variable. Then it won't work and you would then have to check if the string includes the variable that is in your template literal like so:

const customer = {Name: 'bob'}

const str = `My name is ${customer.Name}`

const regex = /\${(.*?)\}/g

const hasIncludedVariable = (str, v) => str.includes(v)

console.log(hasIncludedVariable(str, customer.Name))

  • Related