How to Check if Variable is String in Javascript
You use the typeof
operator in Javascript to check if a variable is a string. The typeof
operator returns a value of string
when the variable is a string.
Simple String Check Example in Javascript
var computerbrands = ["Apple","HP","Dell","Lenovo","Acer","Asus"];
var slogantext = "Road rage burns the tires.";
typeof(computercompanies);
// object
typeof(slogantext);
// string
Using Conditionals
In most instances you will check if a variable an array with an if statement.
var slogantext = "Road rage burns the tires.";
if(typeof(slogantext)=== 'string'){
// Do something if the variable is a string
} else {
// Do something else if the variable is not a string
}
Using a Function
var slogantext = "Road rage burns the tires.";
var computerbrands = ["Apple","HP","Dell","Lenovo","Acer","Asus"];
function checkIfString(variable){
if(typeof(variable)=== 'string'){
return true;
} else {
return false;
}
}
checkIfString(slogantext);
// true
checkIfString(computerbrands);
// false
Displaying Results on a Webpage
Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Check If Variable is String</title>
</head>
<body>
<h1 id="slogan">Waiting for Slogan...</h1>
<script>
var slogantext = "Road rage burns the tires";
var computerbrands = ["Apple","HP","Dell","Lenovo","Acer","Asus"];
var slogan = document.getElementById('slogan');
function checkIfString(variable){
if(typeof(variable)=== 'string'){
slogan.innerHTML(slogantext);
} else {
slogan.innerHTML("No Slogan");
}
}
checkIfString(computerbrands);
checkIfString(slogantext);
</script>
</body>
</html>
Results
You can interact with the complete code on: https://check-string-js.avicndugu.repl.co.