What do you think when you see this topic? This is very simple. Typeof and then determine the length.
if(typeof unknownVariable ==='string' && unknownVariable.length){ ... }
Have you done it?
What if this string is created using new String()? The unknown variable typeof must be object. what would you do?
You definitely have to determine the type first, typeof unknownVariable==='object'? But you have to think that there is also a null variable whose typeof value is also object. Do we need to use && unknownVariable? Now it is a non-empty object. Do we need to check the length? It should not be necessary. But in the end, the typeof object is not necessarily a string object, it can be other objects, such as arrays, json objects, other objects derived from new, etc. What should we do?
This is a rarely used but useful method: valueOf. valueOf will output the original type of the variable.
let str1="test" let str2=new String('test2') let arr1=[1,2,3] let fn1=function(){ console.log('this is a function') } let obj1={ name:'gpd' } let obj2=new Object() obj2.name='gpd' str1.valueOf() // "test" str2.valueOf() //"test2" arr1.valueOf() //[1,2,3] fn1.valueOf() //fn1(){} obj1.valueOf() // {name:"gpd"} obj2.valueOf() // {name:"gpd"}
So, whether you are a string literal or a string object obtained by new String, its valueOf value is a string literal. Then, its typeof values are all string .
So the final judge is
if(typeof unknownVariable !=undefined && unknownVariable && typeof unknowVariable.valueOf() === "string") { ... }
The above is the detailed content of How to determine whether a string exists or is not empty in JS. For more information, please follow other related articles on the PHP Chinese website!