Home  >  Article  >  Web Front-end  >  How to determine whether a string is empty in js

How to determine whether a string is empty in js

coldplay.xixi
coldplay.xixiOriginal
2021-03-01 14:24:2144006browse

JS method to determine whether a string is empty: 1. To determine whether a string is empty, the code is [if (string.length == 0)]; 2. To determine whether a string is an "empty" character That is, the user entered a space, and the code is [if (strings.replace(/(^s*)|(s*$)..].

How to determine whether a string is empty in js

this Tutorial operating environment: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer. This method is suitable for all brands of computers.

JS method to determine whether a string is empty:

Determine whether the string is empty

var strings = ''; 
if (string.length == 0) 
{ 
alert('不能为空'); 
}

Determine whether the string is an "empty" character, that is, the user has entered a space

var strings = ' '; 
if (strings.replace(/(^s*)|(s*$)/g, "").length ==0) 
{ 
alert('不能为空'); 
}

Determine whether the input string is empty or all characters Space

function isNull( str ){
if ( str == "" ) return true;
var regu = "^[ ]+$";
var re = new RegExp(regu);
return re.test(str);
}

If there is null, the above code cannot judge normally. The following code is the case when it is judged as null

var exp = null; 
if (exp == null) 
{ 
alert("is null"); 
}

When exp is undefined, the same result as null will be obtained, although Null and undefined are different.

Note: You can use this method when you want to judge null and undefined at the same time. The code is as follows

var exp = null; 
if (!exp) 
{ 
alert("is null"); 
}

If exp is undefined, or the number zero, or false, you will also get The same result as null, although null is different from the two. Note: This method can be used when you want to judge null, undefined, number zero, and false at the same time. The code is as follows

var exp = null; 
if (typeof exp == "null") 
{ 
alert("is null"); 
}

For backward compatibility, exp is null When, typeof null always returns object, so it cannot be judged this way.

Related free learning recommendations: javascript video tutorial

The above is the detailed content of How to determine whether a string is empty in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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