How to useconstructor property in Javascript
Using the constructor property to check if a variable is a string literal or an object of the String constructor, the constructor property of the input matches String, it is considered a string literal. If the constructor property matches String.prototype.constructor, it is considered an object of the String constructor.
Example: In this example, the check() function uses the constructor property to determine whether the input is a string literal or an object of the String constructor
Javascript
function check(str) { if (str.constructor === String) { return "It is a string literal" ; } else if (str.constructor === String.prototype.constructor) { return "It is an object of string" ; } else { return "Another type" ; } } // Pass a string literal console.log(check( "Hello, Geeks" )); // Pass an object of string let result = new String( "Hello, w3wiki" ); console.log(check(result)); |
Output
It is a string literal It is a string literal
How to test a string as a literal and as an object in JavaScript ?
In this article, we learn how to test a string as a literal and as an object using JavaScript.