Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "instanceof" a primitive string (string literal) in JavaScript [duplicate]

In JavaScript, I can declare a string in the following ways;

var a = "Hello World"; var b = new String("Hello World"); 

but a is not an instance of String...

console.log(a instanceof String); //false; console.log(b instanceof String); //true; 

So how do you find the type or "instanceof" a string literal?

Can JavaScript be forced to create a new String() for every string literal?

like image 226
Matthew Layton Avatar asked May 28 '13 12:05

Matthew Layton


People also ask

How to check instanceof in JavaScript?

The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not. Parameters: objectName: States the name of Object.

How to use backticks in JavaScript?

In that case, the template literal is passed to your tag function, where you can then perform whatever operations you want on the different parts of the template literal. To escape a backtick in a template literal, put a backslash ( \ ) before the backtick.

What is string literal in JavaScript?

Template literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.


2 Answers

use typeof "foo" === "string" instead of instanceof.

like image 101
Artur Udod Avatar answered Sep 23 '22 15:09

Artur Udod


Use typeof instead and just compare the resulting string. See docs for details.

like image 28
isaach1000 Avatar answered Sep 24 '22 15:09

isaach1000