How to check empty/undefined/null string in JavaSc

2018-12-31 03:34发布

I saw this thread, but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?

30条回答
深知你不懂我心
2楼-- · 2018-12-31 04:23

I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:

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

To test its nullness one could do something like this:

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

It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).

查看更多
墨雨无痕
3楼-- · 2018-12-31 04:23

If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:

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

function isBlank(s){
    return isEmpty(s.trim());    
}
查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 04:26

I usually use some thing like this,

if (!str.length) {
//do some thing
}
查看更多
怪性笑人.
5楼-- · 2018-12-31 04:27

For checking if a string is empty, null or undefined I use:

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

For checking if a string is blank, null or undefined I use:

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

For checking if a string is blank or contains only white-space:

String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());
};
查看更多
只靠听说
6楼-- · 2018-12-31 04:27
var s; // undefined
var s = ""; // ""
s.length // 0

There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against ""

查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 04:28

Try this

   str.value.length == 0
查看更多
登录 后发表回答