Home>Article>Web Front-end> How to determine whether a variable is a string in es6
Judgment method: 1. Use the "typeof variable === 'string'" statement; 2. Use "variable instanceof String"; 3. Use "Object.prototype.toString.call(variable)=== "[object String]"".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
es6 Determine whether a variable is a string
Method 1: Use the typeof keyword
## The syntax rules for #typeof are:typeof operand.
typeof a === 'string'to judge. If the return value is true, it is a string.
var a="123456"; typeof a === 'string'; var b=123456; typeof b === 'string';In addition, list some special cases of this operator:
typeof Null; // 'object' typeof NaN; // 'number' typeof Array; // 'object'
Method 2: Using the instanceof keyword
The syntax rule for instanceof isobject instanceof constructor. The return value is of type boolean.
prototypeproperty of the constructor exists on the prototype chain of the object. This means that it can only determine the object type.
new String("I am string") instanceof String;
Method 3: Object.prototype.toString.call()
This method will return "## by default #[object type]", where type is the type of data. It is worth mentioning that call must be used when we call.var a="123456"; Object.prototype.toString.call(a) === "[object String]"; var b=123456; Object.prototype.toString.call(b) === "[object String]";
[Related recommendations:
javascript video tutorialThe above is the detailed content of How to determine whether a variable is a string in es6. For more information, please follow other related articles on the PHP Chinese website!