Search code examples
javascriptstringsyntaxtemplate-literals

Check if a string is a template literal in JavaScript


Is it possible to test if a string is a template literal?

Something like:

const x = "foo"
const y = `${x}bar`  // "foobar"

isTemplateLiteral(x) // false
isTemplateLiteral(y) // true

Solution

  • Template literal is only a syntax/javascript structure, and not a new type of object in the language. The value of the template literal is generated when the processor goes over the line of code and the returned value is a string, hence - you can't check if the value was generated by string literal or by a regular string.

    Btw, if you use babel and you want the output to be valid ES5 - the string literals will be converted to some sort of string concatenate (var y = x + 'bar').