This post will discuss how to check if a variable is a string in JavaScript. The variable can either be a primitive value or an instance of a standard built-in ECMAScript object.

1. Using typeof operator

The recommended solution is to use the typeof operator to determine the type of operand. This is demonstrated below:

Download  Run Code

 
The typeof operator will return an object for strings created with new String(). This can be handled using the instanceof operator.

Download  Run Code

2. Using Object.prototype.toString.call() function

Another approach is to find the class of Objects using the toString method from Object.prototype. You can use this as:

Download  Run Code

3. Using Lodash/Underscore Library

If you’re using the Underscore or Lodash library, consider using the _.isString method, which returns true for the specified value is a string primitive or a string object.

Download Code

4. Using jQuery

With jQuery, the $.type() method can be used to determine the type of object. This works with both primitive string value and built-in String objects. Here’s a working example:

Download Code

That’s all about determining whether a variable is a string in JavaScript.