Summary of js's methods for determining whether an input string is empty blank or null
- 2021-06-28 10:47:50
- OfStack
Determine whether a string is empty
var strings = '';
if (string.length == 0)
{
alert(' Cannot be empty ');
}
Determines 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(' Cannot be empty ');
}
Determine if the input string is empty or all are spaces
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 will not judge properly. The following code is the case for null
var exp = null;
if (exp == null)
{
alert("is null");
}
When exp is undefined, the same results are obtained as null, although null and undefined are not the same.
Note: This law can be used to determine both null and undefined.The code is as follows
var exp = null;
if (!exp)
{
alert("is null");
}
If exp is undefined, or a number of zeros, or false, you will get the same results as null, although null and 2 are not the same.Note: This law can be used to judge null, undefined, Number Zero, false at the same time.The code is as follows
var exp = null;
if (typeof exp == "null")
{
alert("is null");
}
For downward compatibility, when exp is null, typeof null always returns object, so this cannot be judged.
<script type="text/javascript">
function testuser(){
var i= document.getElementByIdx_x("aa");
if (i.value=="null")
{
alert(" Please sign in before posting a message !")
return false;
}
else
{
alert(i.value)
return true;
}
}
</script>