How To Check If A Variable Is A String In JavaScript?
In this tutorial, we will see how to check if a variable is a string in javascript. typeof in js variable is a primitive value or an instance of a standard built-in ES (ECMAScript) object.
Sometimes the string that we get in a project, whether it is in a string or not, check if string javascript, we will see in this tutorial How to find string is string javascript.
We will learn 4 ways how to find out whether a string is there or not.
1. typeof operator
In this step, we will see the recommended solution is to use typeof operator to determine the type of the operand. See below:
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 */
This time typeof
operator will return an object for the string created with a new String().
string javascript can be handled using the instanceof
the operator.
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. Object.prototype.toString.call()
Another example approach is to find the class of object using the toString
method from Object.prototype.
javascript test string this can be used as see below:
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. Lodash/Underscore Library
check if string javascript if you're using the Underscore of Lodash library, consider using the _.isString
a method which returns true for specified value javascript check if string is a string primitive or a String object.
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. jQuery Library
In this step, we will learn how to check type of variable in javascript with jquery, $.type()
a method that can be used to determine the type of object. java script check worked with both primitive string value and built-in String Object. See below:
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 */
I hope it can help you...
Leave a Reply