Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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} ‘

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading