Check if a variable is a string in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
const val = 'Hello World'; if (typeof val === 'string') { console.log('Variable is a string'); } else { console.log('Variable is not a string'); } /* Output: Variable is a string */ |
The typeof operator will return an object for strings created with new String(). This can be handled using the instanceof operator.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
const val = new String('Hello World'); if (typeof val === 'string' || val instanceof String) { console.log('Variable is a string'); } else { console.log('Variable is not a string'); } /* Output: Variable is a string */ |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function isString(x) { return Object.prototype.toString.call(x) === '[object String]'; } const val = 'Hello World'; if (isString(val)) { console.log('Variable is a string'); } else { console.log('Variable is not a string'); } /* Output: Variable is a string */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const _ = require('lodash'); // or underscore const val = new String('Hello World'); if (_.isString(val)) { console.log('Variable is a string'); } else { console.log('Variable is not a string'); } /* Output: Variable is a string */ |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); const $ = require("jquery")(window); const val = 'Hello World'; if ($.type(val) === 'string') { console.log('Variable is a string'); } else { console.log('Variable is not a string'); } /* Output: Variable is a string */ |
That’s all about determining whether a variable is a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)