Home > Web Front-end > JS Tutorial > How to determine whether a string exists or is not empty in JS

How to determine whether a string exists or is not empty in JS

yulia
Release: 2018-09-11 17:29:56
Original
1478 people have browsed it

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){
        ...
    }
Copy after login

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"}
Copy after login

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")
   {
       ...
   }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template