Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
how to detect if variable is a string

How can I detect if a variable is a string?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

This is the way specified in the ECMAScript spec to determine the internal [[Class]] property.

if( Object.prototype.toString.call(myvar) == '[object String]' ) {
   // a string
}

From 8.6.2 Object Internal Properties and Methods:

The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String". The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).


For an example of how this is useful, consider this example:

var str = new String('some string');

alert( typeof str ); // "object"

alert( Object.prototype.toString.call(str) ); // "[object String]"

If you use typeof, you get "object".

But if you use the method above, you get the correct result "[object String]".

over 4 years ago · Santiago Trujillo Report

0

You can use typeof to do it, but for a lot of things this is bad design.

if (typeof myVar == "string") {
    alert("I'm a string!");
}
over 4 years ago · Santiago Trujillo Report

0

Use typeof.

if (typeof foo == 'string')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!