You can simply use the typeof operator to determine or check if a variable is a string in JavaScript.
In the following example just play with the myVar value to see how it works:
// Sample variable
var myVar = 'Hello';
// Test if variable is a string
if(typeof myVar === 'string') {
alert('It is a string.');
} else {
alert('It is not a string.');
You can also define a custom function to check whether a variable is a string or not.
The custom isString() JavaScript function in the following example will return true if the variable is a string otherwise return false. Let's try it out and see how it works:
// Defining a function
function isString(myVar) {
return (typeof myVar === 'string');
}
// Sample variables
var x = 10;
var y = true;
var z = "Hello";
// Testing the variables
alert(isString(x)); // Outputs: false
alert(isString(y)); // Outputs: false
alert(isString(z)); // Outputs: true
Use the
typeofOperatorYou can simply use the
typeofoperator to determine or check if a variable is a string in JavaScript.In the following example just play with the
myVarvalue to see how it works:You can also define a custom function to check whether a variable is a string or not.
The custom isString() JavaScript function in the following example will return true if the variable is a string otherwise return false. Let's try it out and see how it works:
need an explanation for this answer? contact us directly to get an explanation for this answer