Given a variable with some values, the task is to check whether the variable is a string or not in JavaScript.
Approach 1: Using typeof Operator
The typeof
operator is a simple and straightforward way to check the type of a variable in JavaScript. It returns a string indicating the type of the operand.
const variable = "Hello, world!"; if (typeof variable === "string") { console.log("Variable is a string"); } else { console.log("Variable is not a string"); }
Approach 2: Using instanceof Operator
The instanceof
operator checks whether an object belongs to a specific class or constructor function. While this approach is primarily used for checking object instances, it can also be used to check if a variable is a string by comparing it against the String
constructor.
const variable = "Hello, world!"; if (variable instanceof String || typeof variable === "string") { console.log("Variable is a string"); } else { console.log("Variable is not a string"); }
Approach 3: Using typeof and Constructor Property
You can also combine the typeof
operator with the constructor
property of the variable to check if it was created using the String
constructor.
const variable = "Hello, world!"; if (typeof variable === "string" || variable.constructor === String) { console.log("Variable is a string"); } else { console.log("Variable is not a string"); }
Approach 4: Using Regular Expression
You can use a regular expression to test if the variable contains only characters typical of a string. If the test passes, it’s likely a string.
const variable = "Hello, world!"; if (/^[a-zA-Z\s]*$/.test(variable)) { console.log("Variable is a string"); } else { console.log("Variable is not a string"); }