Skip to content Skip to sidebar Skip to footer

Detecting Template Literals In Javascript

We have two potential values: const value = `Hello World`; and const value = {message: 'Hello World'}; What I'm trying to do is a conditional where if(is template literal) {

Solution 1:

There is no difference between using a string literal and a template literal (except, obviously, on the source code level).

But your first value is a string, while the second one is an object, and those are easy to distinguish:

if (typeof value == "string") {
    console.log(value)
} elseif (typeof value == "object" && typeof value.message == "string") {
    console.log(value.message)
}

Post a Comment for "Detecting Template Literals In Javascript"