How to check if a variable is a string in javascript ?

Active February 15, 2022    /    Viewed 195    /    Comments 0    /    Edit


Examples of how to check if a variable is a string in javascript:

String variable

Create a string

var s = 'Hello world !'

to check if it is a string a solution is to use typeof:

console.log(typeof s === 'string');

gives here

true

Check if it is a string object:

console.log(s instanceof String);

gives

false

String object

Create a string object

var sobj  = new String('Hello World !');

console.log(typeof sobj === 'string');

gives

false

while

console.log(sobj instanceof String);

gives now

true

Test if it is a string or a string object

Other examples check if it is a string or a string object.

Example 1:

var s = 'Hello world !'
if (typeof s === 'string' || s instanceof String)
{console.log("YES"); }
else
{console.log("NO"); }

gives

YES

Example 2:

var s = new String('Hello World !');
if (typeof s === 'string' || s instanceof String)
{console.log("YES"); }
else
{console.log("NO"); }

gives

YES

Example 3:

var s = 1234
if (typeof s === 'string' || s instanceof String)
{console.log("YES"); }
else
{console.log("NO"); }

gives

NO

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount