Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 698
Dan Mandel Avatar asked Dec 26 '17 18:12

Dan Mandel


1 Answers

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').

like image 120
Dekel Avatar answered Oct 23 '22 23:10

Dekel