Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a variable is a string in JavaScript

How can I determine whether a variable is a string or something else in JavaScript?

like image 499
Olical Avatar asked Oct 30 '10 14:10

Olical


People also ask

How do you check if a variable is a string in JavaScript?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string.

How do I check if a variable is number or string?

In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.

How do you check if a variable is a string in TypeScript?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.

What is this ${} in JavaScript?

${} is a placeholder that is used in template literals. You can use any valid JavaScript expression such as variable, arithmetic operation, function call, and others inside ${}. The expression used inside ${} is executed at runtime, and its output is passed as a string to template literals.


2 Answers

This is what works for me:

if (typeof myVar === 'string' || myVar instanceof String) // it's a string else // it's something else 
like image 76
DRAX Avatar answered Oct 12 '22 13:10

DRAX


You can use typeof operator:

var booleanValue = true;  var numericalValue = 354; var stringValue = "This is a String"; var stringObject = new String( "This is a String Object" ); alert(typeof booleanValue) // displays "boolean" alert(typeof numericalValue) // displays "number" alert(typeof stringValue) // displays "string" alert(typeof stringObject) // displays "object" 

Example from this webpage. (Example was slightly modified though).

This won't work as expected in the case of strings created with new String(), but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.


  1. The Google JavaScript Style Guide says to never use primitive object wrappers.
  2. Douglas Crockford recommended that primitive object wrappers be deprecated.
like image 25
Pablo Santa Cruz Avatar answered Oct 12 '22 11:10

Pablo Santa Cruz