Check if a variable is a string using JavaScript
Last Updated :
20 Aug, 2024
Checking if a variable is a string in JavaScript is a common task to ensure that the data type of a variable is what you expect. This is particularly important when handling user inputs or working with dynamic data, where type validation helps prevent errors and ensures reliable code execution.
Below are the following methods through which we can check the type of variable is a string:
Using typeOf Operator
In this approach, we are using typeOf operator which tells us the type of the given value. we are getting the type of the value by the use of the typeOf operator and we are using if-else for returning our ans.
Example: This example shows the implementation of the above-explained approach.
JavaScript
let boolValue = true;
let numValue = 17;
let bool, num;
if (typeof boolValue == "string") {
bool = "is a string";
} else {
bool = "is not a string";
}
if (typeof numValue == "string") {
num = "is a string";
} else {
num = "is not a string";
}
console.log(bool);
console.log(num);
Outputis not a string
is not a string
Using Instanceof Operator
The instanceof operator in JavaScript is used to check the type of an object at run time.
Syntax:
let gfg = objectName instanceof objectType
Example: This example shows the implementation of above-explained appraoch.
JavaScript
let variable = new String();
if (variable instanceof String) {
console.log("variable is a string.");
} else {
console.log("variable is not a string.");
}
Outputvariable is a string.
Underscore.js _.isString()
The _.isString() function is used to check whether the given object element is string or not.
Syntax:
_.isString( object );
Example: This example shows the implementation of above-explained appraoch.
JavaScript
let _ = required("underscore");
let info = {
Company: 'GeeksforGeeks',
Address: 'Noida',
Contact: '+91 9876543210'
};
console.log(_.isString(info));
let str = 'GeeksforGeeks';
console.log(_.isString(str));
Output:
false
true
Using Lodash _.isString() Method
In this approach, we are using the Lodah _.isString() method that returns boolean response for the given value.
Example: This example shows the implementation of above-explained appraoch.
JavaScript
// Requiring the lodash library
const _ = require("lodash");
// Use of _.isString() method
console.log(_.isString('GeeksforGeeks'));
console.log(_.isString(true));
Output:
true
false
Using Object.prototype.toString.call Method
The Object.prototype.toString.call method is a reliable way to determine the type of a variable. It returns a string indicating the type of the object.
Syntax:
Object.prototype.toString.call(variable) === '[object String]'
Example: This example shows the implementation of the above-explained approach.
JavaScript
function checkIfString(variable) {
if (Object.prototype.toString.call(variable) === '[object String]') {
console.log("variable is a string.");
} else {
console.log("variable is not a string.");
}
}
// Test cases
checkIfString("Hello, World!");
checkIfString(42);
checkIfString(true);
checkIfString({});
checkIfString(new String("Test"));
Outputvariable is a string.
variable is not a string.
variable is not a string.
variable is not a string.
variable is a string.
Similar Reads
Check if a Variable is of Function Type using JavaScript A function in JavaScript is a set of statements used to perform a specific task. A function can be either a named one or an anonymous one. The set of statements inside a function is executed when the function is invoked or called. javascriptlet gfg = function(){/* A set of statements */};Here, an an
3 min read
How to Check if a Variable is an Array in JavaScript? To check if a variable is an array, we can use the JavaScript isArray() method. It is a very basic method to check a variable is an array or not. Checking if a variable is an array in JavaScript is essential for accurately handling data, as arrays have unique behaviors and methods. Using JavaScript
2 min read
How to check if a Variable Is Not Null in JavaScript ? In JavaScript, checking if a variable is not null ensures that the variable has been assigned a value and is not empty or uninitialized. This check is important for avoiding errors when accessing or manipulating data, ensuring that the variable holds valid, usable content before proceeding with oper
4 min read
How to check if a string is html or not using JavaScript? The task is to validate whether the given string is valid HTML or not using JavaScript. we're going to discuss a few techniques. Approach Get the HTML string into a variable.Create a RegExp which checks for the validation.RegExp should follow the rules of creating an HTML document. Example 1: In thi
2 min read
JavaScript - How To Check Whether a String Contains a Substring? Here are the different methods to check whether a string contains a substring in JavaScript.1. Using includes() MethodThe includes() method is the most simple and modern way to check if a string contains a specific substring. It returns true if the substring is found within the string, and false oth
3 min read
How to Check if a Value is a Number in JavaScript ? To check if a value is a number in JavaScript, use the typeof operator to ensure the value's type is 'number'. Additionally, functions like Number.isFinite() and !isNaN() can verify if a value is a valid, finite number.Methods to Check if a Value is a NumberThere are various ways to check if a value
3 min read
Check if Strings are Equal in JavaScript These are the following ways to check for string equality in JavaScript:1. Using strict equality operator - Mostly UsedThis operator checks for both value and type equality. it can be also called as strictly equal and is recommended to use it mostly instead of double equals.JavaScriptlet s1 = 'abc';
2 min read
Check if a Given String is Binary String or Not in JavaScript Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it's every character present in the string.Example:Input: "101010"Output: True, bin
3 min read
JavaScript Check the existence of variable JavaScript has a built-in function to check whether a variable is defined/initialized or undefined. To do this, we will use the typeof operator. The typeof operator will return undefined if the variable is not initialized and the operator will return null if the variable is left blank intentionally.
2 min read
Validate a password using HTML and JavaScript Validating a password using HTML and JavaScript involves ensuring that user-entered passwords meet certain criteria, such as length, complexity, or character types (e.g., uppercase, lowercase, numbers, and symbols). This process enhances security by enforcing strong password requirements before form
2 min read