我看到了这个主题,但我没有看到JavaScript特定的例子。 JavaScript中是否有简单的 string.Empty ,或者只是检查""

有帮助吗?

解决方案

如果您只是想检查是否有值,可以

if (strValue) {
    //do something
}

如果您需要专门检查null上的空字符串,我认为使用"" 是最好的选择。 /js/column26/stricteq.html"rel =“noreferrer”> === 运算符(这样你就知道它实际上是一个你正在比较的字符串)。

if (strValue === "") {
    //...
}

其他提示

为了检查字符串是否为空,null或未定义,我使用:

function isEmpty(str) {
    return (!str || 0 === str.length);
}

为了检查字符串是否为空,null或未定义,我使用:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

检查字符串是否为空或仅包含空格:

String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());
};

以上所有都很好,但这会更好。使用 !! not not )运算符。

if(!!str){
some code here;
}

或使用类型转换:

if(Boolean(str)){
    codes here;
}

两者都做同样的函数,输入变量为boolean,其中 str 是变量。
null,undefined,0,000,"",false 返回 false
返回字符串“0”的 true 和空白“ "

如果你需要确保字符串不只是一堆空格(我假设这是用于表单验证),你需要对空格进行替换。

if(str.replace(/\s/g,"") == ""){
}

你最接近 str.Empty (前提是str是一个字符串)是:

if (!str.length) { ...

我用:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case typeof this == "undefined":
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
  })) // false

尝试:

if (str && str.trim().length) {  
    //...
}

功能:

function is_empty(x)
{
   return ( 
        (typeof x == 'undefined')
                    ||
        (x == null) 
                    ||
        (x == false)  //same as: !x
                    ||
        (x.length == 0)
                    ||
        (x == "")
                    ||
        (x.replace(/\s/g,"") == "")
                    ||
        (!/[^\s]/.test(x))
                    ||
        (/^\s*$/.test(x))
  );
}
  

P.S。在Javascript中,不要在 return ;

之后使用换行符
var s; // undefined
var s = ""; // ""
s.length // 0

JavaScript中没有任何代表空字符串的内容。检查 length (如果你知道var将始终是一个字符串)或""

您可以使用 lodash : _.isEmpty(值)。

它涵盖了很多案例,例如 {} '' null undefined 等。

但它始终返回 true Number 类型 Javascript原始数据类型,如 _。isEmpty(10) _。isEmpty(Number.MAX_VALUE)都返回<代码>真

我不会过分关注最强高效方法。使用最明确的意图。对我来说,通常是 strVar ==&quot;&quot;

编辑:来自 Constantin 的评论,如果strVar可能会有一些结果包含整数0值,那么确实是那些意图澄清的情况之一。

你也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查空格或填充空格的字符串。

很多答案,以及很多不同的可能性!

毫无疑问,快速简单的实施方案是: if(!str.length){...}

然而,正如许多其他例子一样。我建议最好的功能方法:

function empty(str)
{
    if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
    {
        return true;
    }
    else
    {
        return false;
    }
}

有点过分,我知道。

  1. 检查 var a; 是否存在
  2. 修剪出值中的 false spaces ,然后测试空白

    if ((a)&&(a.trim()!=''))
    {
      // if variable a is not empty do this 
    }
    

此外,如果您将填充空格的字符串视为“空”。 您可以使用此正则表达式进行测试:

!/\S/.test(string); // Returns true if blank.

我经常使用这样的东西,

if (!str.length) {
//do some thing
}

我没有注意到一个考虑到字符串中空字符可能性的答案。例如,如果我们有一个空字符串:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

要测试其无效性,可以执行以下操作:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

它适用于空字符串,并且在空字符串上,所有字符串都可以访问它。此外,它可以扩展为包含其他JavaScript空或空白字符(即不间断空格,字节顺序标记,行/段分隔符等)。

如果一个人不仅要检测空字符串还需要空白字符串,我会添加Goral的答案:

function isEmpty(s){
    return !s.length;    
}

function isBlank(s){
    return isEmpty(s.trim());    
}

所有这些答案都很好。

但我不能确定变量是一个字符串,不包含空格(这对我很重要),并且可以包含'0'(字符串)。

我的版本:

function empty(str){
    return !str || !/[^\s]+/.test(str);
}

empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty("  "); // true

jsfiddle 上的示例。

我通常使用类似的东西:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}

我使用组合,最快速检查。

function isBlank(pString){
    if (!pString || pString.length == 0) {
        return true;
    }
    // checks for a non-white space character 
    // which I think [citation needed] is faster 
    // than removing all the whitespace and checking 
    // against an empty string
    return !/[^\s]+/.test(pString);
}

忽略空白字符串,您可以使用它来检查null,empty和undefined:

var obj = {};
(!!obj.str) //returns false

obj.str = "";
(!!obj.str) //returns false

obj.str = null;
(!!obj.str) //returns false

简洁,它适用于未定义的属性,尽管它不是最易读的。

我做了一些研究,如果将非字符串和非空/空值传递给测试器函数会发生什么。众所周知,(0 ==&quot;&quot;)在javascript中是正确的,但由于0是一个值而不是空或null,您可能想要测试它。

以下两个函数仅对undefined,null,empty / whitespace值返回true,对其他所有值返回false,如数字,布尔值,对象,表达式等。

function IsNullOrEmpty(value)
{
    return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
    return (value == null || !/\S/.test(value));
}

存在更复杂的例子,但这些例子很简单并且给出了一致的结果。没有必要测试undefined,因为它包含在(value == null)检查中。您也可以通过将它们添加到String来模仿C#行为,如下所示:

String.IsNullOrEmpty = function (value) { ... }

你不想把它放在Strings原型中,因为如果String-class的实例为null,它将会出错:

String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error

我使用以下值数组进行了测试。如果有疑问,你可以循环测试你的功能。

// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
    ['undefined', undefined],
    ['(var) z', z],
    ['null', null],
    ['empty', ''],
    ['space', ' '],
    ['tab', '\t'],
    ['newline', '\n'],
    ['carriage return', '\r'],
    ['"\\r\\n"', '\r\n'],
    ['"\\n\\r"', '\n\r'],
    ['" \\t \\n "', ' \t \n '],
    ['" txt \\t test \\n"', ' txt \t test \n'],
    ['"txt"', "txt"],
    ['"undefined"', 'undefined'],
    ['"null"', 'null'],
    ['"0"', '0'],
    ['"1"', '1'],
    ['"1.5"', '1.5'],
    ['"1,5"', '1,5'], // valid number in some locales, not in js
    ['comma', ','],
    ['dot', '.'],
    ['".5"', '.5'],
    ['0', 0],
    ['0.0', 0.0],
    ['1', 1],
    ['1.5', 1.5],
    ['NaN', NaN],
    ['/\S/', /\S/],
    ['true', true],
    ['false', false],
    ['function, returns true', function () { return true; } ],
    ['function, returns false', function () { return false; } ],
    ['function, returns null', function () { return null; } ],
    ['function, returns string', function () { return "test"; } ],
    ['function, returns undefined', function () { } ],
    ['MyClass', MyClass],
    ['new MyClass', new MyClass()],
    ['empty object', {}],
    ['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
    ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
    ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];

检查是否完全是空字符串:

if(val==="")...

检查它是否为空字符串或无值的逻辑等效项(null,undefined,0,NaN,false,...):

if(!val)...

与此同时,我们可以使用一个函数来检查所有'空虚',例如 null,undefined,'','',{},[] 。 所以我写了这篇文章。

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

用例和结果。

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

没有 isEmpty()方法,你必须检查类型和长度:

if (typeof test === 'string' && test.length === 0){
  ...

test undefined null 时,需要进行类型检查以避免运行时错误。

不要假设您检查的变量是字符串。不要假设如果这个var有一个长度,那么它就是一个字符串。

问题是:仔细考虑您的应用必须做和可以接受的内容。建立健全的东西。

如果你的方法/函数只应处理非空字符串,那么测试参数是否为非空字符串并且不要做一些“技巧”。

作为一个例子,如果你在这里不小心遵循一些建议就会爆炸。


var getLastChar = function (str) {
 if (str.length > 0)
   return str.charAt(str.length - 1)
}

getLastChar('hello')
=> "o"

getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'

所以,我坚持


if (myVar === '')
  ...

试试这个

str.value.length == 0

您可以轻松地将其添加到 JavaScript 中的原生字符串对象,并一遍又一遍地重复使用...
如果你想检查''空字符串,那么像下面的代码这样简单的东西可以帮你完成工作:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
  return !(!!this.length);
}

否则,如果你想用空格检查''空字符串和'',你可以通过添加 trim()<来实现。 / code>,类似下面的代码:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
   return !(!!this.trim().length);
}

你可以这样称呼它:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;

now you can check if your string is empty as like 
if(plen==0)
{
         alert('empty');
}
else
{
   alert('you entered something');
}
}


<input type='text' id='pasword' />

这也是检查字段是否为空的通用方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top