One of the easiest ways we can use JavaScript to check if a variable is a string is by using the JavaScript typeof Operator in an if conditional statement.

if ( typeof someVariable == "string" ){
  //The variable IS a string
}

In the code above, someVariable is the variable that we want to check to see if it is a string. typeof someVariable will return “string” if the variable is a string, and therefore the conditional statement will be true.

We can put this code in a function to make checking if a variable is a string very simple.

Here is the function:

function isString(variable){
  if ( typeof variable == "string" ){
    return true;
  } else {
    return false;  
  }
};

Our function simply returns true if the variable you enter is a string, and false if not.

Now let’s show some examples of this function is use:

function isString(variable){
  if ( typeof variable == "string" ){
    return true;
  } else {
    return false;  
  }
};

var variable1 = "a string";
var variable2 = 1234;
var variable3 = "1234";
var variable4 = true;
var variable5 = "true";
var variable6 = "";

console.log(isString(variable1));
console.log(isString(variable2));
console.log(isString(variable3));
console.log(isString(variable4));
console.log(isString(variable5));
console.log(isString(variable6));

#Output:
true
false
true
false
true
true

Hopefully this article has been useful for you to learn how to use JavaScript to check if a variable is a string.

Categorized in:

JavaScript,

Last Update: March 22, 2024