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*$)..].
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.
<script type="text/javascript"> function testuser(){ var i= document.getElementByIdx_x("aa"); if (i.value=="null") { alert("请登录后再发表留言!") return false; } else { alert(i.value) return true; } } </script>
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!