Examples of how to check if a variable is a string in javascript:
Table of contents
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