JavaScript 如何检查空/未定义/空字符串

JavaScript 如何检查空/未定义/空字符串

如果我们想要检查任何字符串是否为空或填充,我们可以使用JavaScript来实现这个目的,例如: 表单验证 。

示例:

<script> 
    function checkempty(form) { 
        if (form.name.value == null || 
            form.name.value == undefined || 
            form.name.value.length == 0) { 
          
            alert("Name cannot be empty\n"); 
            return false; 
        } else { 
            alert("Your response has been recorded\n"); 
            return true; 
        } 
    } 
</script> 
<form onsubmit="return checkempty(form1)" action="#" method="post" name="form1"> 
    <label>Enter your name</label> 
    <br> 
    <input type="string" placeholder="Enter name" name="name" /> 
    <br> 
    <br> 
    <label>Enter Email</label> 
    <br> 
    <input type="" placeholder="Enter email" name="email" /> 
    <br> 
    <br> 
    <label>Enter password</label> 
    <br> 
    <input type="password" placeholder="Enter password " name="password1" /> 
    <br> 
    <br> 
    <label>Confirm password</label> 
    <br> 
    <input type="password" placeholder="Enter password " name="password2" /> 
    <br> 
    <br> 
    <input type="submit" value="submit" /> 
    <br> 
</form>

输出: 如果名称为空。

JavaScript 如何检查空/未定义/空字符串

用3种不同的方法进行简化

方法1:使用===运算符

使用===运算符检查字符串是否为空。如果为空,则返回“空字符串”,如果字符串不为空,则返回“非空字符串”。

// function to check string is empty or not 
function checking(str){ 
// checking the string using === operator 
    if (str === "") { 
        console.log("Empty String") 
    } 
    else { 
       console.log("Not Empty String") 
    } 
} 
  
// calling the checking function with empty string 
checking("") 
// calling the checking function with not an empty string 
checking("GeeksforGeeks")

输出:

Empty String
Not Empty String

方法2:通过使用长度和运算符

这个函数将检查字符串的长度,同时通过使用运算符来检查字符串是否为空。

// function to check string is empty or not 
function checking(str) { 
    // checking the string using ! operator and length 
    // will return true if empty string and false if string is not empty 
    return (!str || str.length === 0 ); 
} 
// calling the checking function with empty string 
console.log(checking("")) 
// calling the checking function with not an empty string 
console.log(checking("GeeksforGeeks"))

输出:

true
false

方法3:使用replace方法

这将确保字符串不仅仅是一组空格,我们将在其中替换空格。

// function to check string is empty or not 
function checking(str){ 
    if(str.replace(/\s/g,"") == ""){ 
        console.log("Empty String") 
    } 
    else{ 
        console.log("Not Empty String") 
    } 
} 
  
// calling the checking function with empty string 
checking("  ") 
// calling the checking function with not an empty string 
checking("Hello Javascript")

输出:

Empty String
Not Empty String

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程