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 ""
?
我看到了这个线程,但是我没有看到一个JavaScript特定的例子。有一个简单的字符串。在JavaScript中是空的,还是只需要检查一下?
39 个解决方案
#1
2613
If you just want to check whether there's any value, you can do
如果你想检查是否有任何值,你可以。
if (strValue) {
//do something
}
If you need to check specifically for an empty string over null, I would think checking against ""
is your best bet, using the ===
operator (so that you know that it is, in fact, a string you're comparing against).
如果您需要专门检查空字符串,那么我认为检查“”是您最好的选择,使用===操作符(这样您就知道它实际上是一个您正在比较的字符串)。
#2
867
For checking if a string is empty, null or undefined I use:
用于检查字符串是否为空、null或未定义的I:
function isEmpty(str) {
return (!str || 0 === str.length);
}
For checking if a string is blank, null or undefined I use:
用于检查字符串是否为空、空或未定义的I使用:
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());
};
#3
212
All the above are good but this will be even better. use !!
(not not) operator.
以上这些都很好,但这将会更好。使用! !(不)算子。
if(!!str){
some code here;
}
or use type casting:
或者使用类型铸造:
if(Boolean(str)){
codes here;
}
Both do the same function, type cast the variable to boolean, where str
is a variable.
Returns false
for null,undefined,0,000,"",false
.
Returns true
for string "0" and whitespace " ".
两者都执行相同的功能,类型将变量转换为boolean,其中str是一个变量。0000年为空返回false,未定义的,“”,假的。返回true,字符串“0”和空格“”。
#4
84
If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.
如果您需要确保字符串不只是一堆空空间(我假设这是表单验证),那么您需要在空格上做一个替换。
if(str.replace(/\s/g,"") == ""){
}
#5
74
The closest thing you can get to str.Empty (with the precondition that str is a String) is:
您可以访问的最接近的东西是:empty(具有str为字符串的前提条件)为:
if (!str.length) { ...
#6
40
I use :
我使用:
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
#7
24
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 ""
JavaScript中没有表示空字符串的东西。对任意长度进行检查(如果您知道var始终是字符串)或“”
#8
22
I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == ""
.
我不会太担心最有效的方法。使用最清晰的意图。对我来说,通常是strVar == "
EDIT: per comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.
编辑:来自Constantin的评论,如果strVar可能有一些最终包含一个整数0值,那么这将确实是一种意图澄清的情况。
#9
21
Try:
试一试:
if (str && str.trim().length) {
//...
}
#10
18
Function:
功能:
function Is_Empty_or_Undefined (MyVar){ return (
(typeof MyVar== 'undefined') //undefined
||
(MyVar == null) //null
||
(MyVar == false) //!MyVariable //false
||
(MyVar.length == 0) //empty
||
(MyVar == "") //empty
||
(MyVar.replace(/\s/g,"") == "") //empty
||
(!/[^\s]/.test(MyVar)) //empty
||
(/^\s*$/.test(MyVar)) //empty
);
}
#11
17
you could also go with regexps:
你也可以选择regexp:
if((/^\s*$/).test(str)) { }
Checks for strings that are either empty or filled with whitespace.
检查空的或填充空白的字符串。
#12
13
- check that
var a;
exist - 检查,var;存在
-
trim out the
false spaces
in the value, then test foremptiness
在值中去掉假空格,然后测试空值。
if ((a)&&(a.trim()!='')) { // if variable a is not empty do this }
#13
12
A lot of answers, and a lot of different possibilities!
有很多答案,还有很多不同的可能性!
Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}
毫无疑问,快速而简单的实现方法是:if (! string .length){…}
However, as many other examples are available. The best functional method to go about this, I would suggest:
然而,还有许多其他的例子。最好的函数方法是,我建议:
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;
}
}
#14
11
Also, in case you consider a whitespace filled string as "empty". You can test it with this Regex:
同样,如果您认为空格填充的字符串是“空的”。您可以使用这个Regex测试它:
!/\S/.test(string); // Returns true if blank.
#15
11
You can use lodash : _.isEmpty(value).
您可以使用lodash: _.isEmpty(值)。
It covers a lot of cases like {}
, ''
, null
, undefined
etc.
它涵盖了许多像{},“,空,未定义等”的例子。
But it always returns true
for Number
type of Javascript Primitive Data Types like _.isEmpty(10)
or _.isEmpty(Number.MAX_VALUE)
both returns true
.
但是,它总是返回true,用于Javascript原始数据类型,如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)返回true。
#16
9
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.).
它在空字符串上工作,并且在空字符串上,它对所有字符串都是可访问的。此外,它还可以扩展为包含其他JavaScript空字符或空格字符(即不间断空格、字节顺序标记、行/段落分隔符等)。
#17
9
I usually use some thing like this,
我通常用这样的东西,
if (!str.length) {
//do some thing
}
#18
8
If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:
如果需要检测的不仅是空的字符串,我还会添加Goral的答案:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
#19
7
I use a combination, fastest checks are first.
我使用组合,最快的检查是第一。
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);
}
#20
7
Ignoring whitespace strings, you could use this to check for null, empty and undefined :
忽略空白字符串,可以使用它检查null、空和未定义:
var obj = {};
(!!obj.str) //returns false
obj.str = "";
(!!obj.str) //returns false
obj.str = null;
(!!obj.str) //returns false
Concise and it works for undefined properties, although it's not the most readable.
简洁,它适用于未定义的属性,尽管它不是最易读的。
#21
7
All these answers are nice.
所有这些答案都很好。
But I cannot be sure that variable is a string, doesn't contains only spaces (this is important for me), and can contain '0' (string).
但是我不能确定变量是字符串,不包含空格(这对我来说很重要),并且可以包含“0”(字符串)。
My version:
我的版本:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Sample on jsfiddle.
jsfiddle样本。
#22
6
I usually use something like:
我通常用:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
#23
6
I did some research what happens if you pass a non-string and non-empty/null value to a tester function. As many knows, (0 == "") is true in javascript, but since 0 is a value and not empty or null, you may want to test for it.
我做了一些研究,如果您将一个非字符串和非空/空值传递给测试函数,会发生什么情况。正如许多人所知道的,(0 == ")在javascript中是正确的,但是由于0是一个值,而不是空的或空的,所以您可能想要测试它。
The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, boolean, objects, expressions etc.
以下两个函数只返回对未定义的、null、空/空格值和其他所有值的错误,如数字、布尔、对象、表达式等。
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:
更复杂的例子是存在的,但是这些例子很简单,并且给出了一致的结果。没有必要对未定义的进行测试,因为它包含在(value == null)检查中。您还可以通过将它们添加到字符串中来模拟c#行为:
String.IsNullOrEmpty = function (value) { ... }
You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:
您不希望将它放在字符串原型中,因为如果string类的实例为null,那么它将会出错:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error
I tested with the following value array. You can loop it through to test your functions if in doubt.
我使用以下值数组进行了测试。如果有疑问,可以通过循环来测试函数。
// 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; } }]
];
#24
6
to check if is exactly an empty string:
检查是否为空字符串:
if(val==="")...
to check if it is an empty string OR a a logical equivalent for no-value (null, undefined, 0, NaN, false, ...):
检查它是否是一个空字符串或一个逻辑等价的无值(null,未定义,0,NaN, false,…):
if(!val)...
#25
5
There's no isEmpty()
method, you have to check for the type and the length:
没有isEmpty()方法,您必须检查类型和长度:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test
is undefined
or null
.
当测试未定义或null时,需要类型检查以避免运行时错误。
#26
5
Try this
试试这个
str.value.length == 0
#27
4
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' />
this is also a generic way to check if field is empty.
这也是检查字段是否为空的通用方法。
#28
4
Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.
不要假设您检查的变量是字符串。不要假设这个var有一个长度,那么它就是一个字符串。
The thing is: think carefully about what your app must do and can accept. Build something robust.
问题是:仔细考虑你的应用必须做什么,并能接受。构建健壮的东西。
If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.
如果您的方法/函数只处理一个非空字符串,那么测试参数是否为非空字符串,并且不执行一些“技巧”。
As an example of something that will explode if you follow some advices here not carefully.
作为一个例子,如果你遵循一些建议将会爆炸,这里不小心。
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'
So, I'd stick with
所以,我坚持
if (myVar === '')
...
#29
3
You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution:
您也应该经常检查类型,因为JavaScript是鸭子类型的语言,所以您可能不知道什么时候以及如何在过程中间更改数据。所以,这里有一个更好的解决方案:
var str = "";
if (str === "") {
//...
}
#30
3
The underscore javascript library http://underscorejs.org/ provides a very useful _.isEmpty()
function for checking for empty strings and other empty objects.
下划线javascript库http://underscorejs.org/提供了一个非常有用的_.isEmpty()函数,用于检查空字符串和其他空对象。
Reference: http://underscorejs.org/#isEmpty
参考:http://underscorejs.org/ isEmpty
isEmpty
_.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.isEmpty _.isEmpty(对象)返回true,如果一个可枚举对象不包含值(没有可枚举的自属性)。对于字符串和类似数组的对象_。isEmpty检查长度属性是否为0。
_.isEmpty([1, 2, 3]);
=> false_。isEmpty([1,2,3]);= >假
_.isEmpty({});
=> true_.isEmpty({ });= > true
Other very useful underscore functions include:
http://underscorejs.org/#isNull _.isNull(object)
http://underscorejs.org/#isUndefined _.isUndefined(value)
http://underscorejs.org/#has _.has(object, key)
其他非常有用的下划线函数包括:http://underscorejs.org/#isNull _.isNull(对象)http://underscorejs.org/#isUndefined _.isUndefined(value) http://underscorejs.org/#有_。(对象,键)
#1
2613
If you just want to check whether there's any value, you can do
如果你想检查是否有任何值,你可以。
if (strValue) {
//do something
}
If you need to check specifically for an empty string over null, I would think checking against ""
is your best bet, using the ===
operator (so that you know that it is, in fact, a string you're comparing against).
如果您需要专门检查空字符串,那么我认为检查“”是您最好的选择,使用===操作符(这样您就知道它实际上是一个您正在比较的字符串)。
#2
867
For checking if a string is empty, null or undefined I use:
用于检查字符串是否为空、null或未定义的I:
function isEmpty(str) {
return (!str || 0 === str.length);
}
For checking if a string is blank, null or undefined I use:
用于检查字符串是否为空、空或未定义的I使用:
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());
};
#3
212
All the above are good but this will be even better. use !!
(not not) operator.
以上这些都很好,但这将会更好。使用! !(不)算子。
if(!!str){
some code here;
}
or use type casting:
或者使用类型铸造:
if(Boolean(str)){
codes here;
}
Both do the same function, type cast the variable to boolean, where str
is a variable.
Returns false
for null,undefined,0,000,"",false
.
Returns true
for string "0" and whitespace " ".
两者都执行相同的功能,类型将变量转换为boolean,其中str是一个变量。0000年为空返回false,未定义的,“”,假的。返回true,字符串“0”和空格“”。
#4
84
If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.
如果您需要确保字符串不只是一堆空空间(我假设这是表单验证),那么您需要在空格上做一个替换。
if(str.replace(/\s/g,"") == ""){
}
#5
74
The closest thing you can get to str.Empty (with the precondition that str is a String) is:
您可以访问的最接近的东西是:empty(具有str为字符串的前提条件)为:
if (!str.length) { ...
#6
40
I use :
我使用:
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
#7
24
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 ""
JavaScript中没有表示空字符串的东西。对任意长度进行检查(如果您知道var始终是字符串)或“”
#8
22
I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == ""
.
我不会太担心最有效的方法。使用最清晰的意图。对我来说,通常是strVar == "
EDIT: per comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.
编辑:来自Constantin的评论,如果strVar可能有一些最终包含一个整数0值,那么这将确实是一种意图澄清的情况。
#9
21
Try:
试一试:
if (str && str.trim().length) {
//...
}
#10
18
Function:
功能:
function Is_Empty_or_Undefined (MyVar){ return (
(typeof MyVar== 'undefined') //undefined
||
(MyVar == null) //null
||
(MyVar == false) //!MyVariable //false
||
(MyVar.length == 0) //empty
||
(MyVar == "") //empty
||
(MyVar.replace(/\s/g,"") == "") //empty
||
(!/[^\s]/.test(MyVar)) //empty
||
(/^\s*$/.test(MyVar)) //empty
);
}
#11
17
you could also go with regexps:
你也可以选择regexp:
if((/^\s*$/).test(str)) { }
Checks for strings that are either empty or filled with whitespace.
检查空的或填充空白的字符串。
#12
13
- check that
var a;
exist - 检查,var;存在
-
trim out the
false spaces
in the value, then test foremptiness
在值中去掉假空格,然后测试空值。
if ((a)&&(a.trim()!='')) { // if variable a is not empty do this }
#13
12
A lot of answers, and a lot of different possibilities!
有很多答案,还有很多不同的可能性!
Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}
毫无疑问,快速而简单的实现方法是:if (! string .length){…}
However, as many other examples are available. The best functional method to go about this, I would suggest:
然而,还有许多其他的例子。最好的函数方法是,我建议:
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;
}
}
#14
11
Also, in case you consider a whitespace filled string as "empty". You can test it with this Regex:
同样,如果您认为空格填充的字符串是“空的”。您可以使用这个Regex测试它:
!/\S/.test(string); // Returns true if blank.
#15
11
You can use lodash : _.isEmpty(value).
您可以使用lodash: _.isEmpty(值)。
It covers a lot of cases like {}
, ''
, null
, undefined
etc.
它涵盖了许多像{},“,空,未定义等”的例子。
But it always returns true
for Number
type of Javascript Primitive Data Types like _.isEmpty(10)
or _.isEmpty(Number.MAX_VALUE)
both returns true
.
但是,它总是返回true,用于Javascript原始数据类型,如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)返回true。
#16
9
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.).
它在空字符串上工作,并且在空字符串上,它对所有字符串都是可访问的。此外,它还可以扩展为包含其他JavaScript空字符或空格字符(即不间断空格、字节顺序标记、行/段落分隔符等)。
#17
9
I usually use some thing like this,
我通常用这样的东西,
if (!str.length) {
//do some thing
}
#18
8
If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:
如果需要检测的不仅是空的字符串,我还会添加Goral的答案:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
#19
7
I use a combination, fastest checks are first.
我使用组合,最快的检查是第一。
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);
}
#20
7
Ignoring whitespace strings, you could use this to check for null, empty and undefined :
忽略空白字符串,可以使用它检查null、空和未定义:
var obj = {};
(!!obj.str) //returns false
obj.str = "";
(!!obj.str) //returns false
obj.str = null;
(!!obj.str) //returns false
Concise and it works for undefined properties, although it's not the most readable.
简洁,它适用于未定义的属性,尽管它不是最易读的。
#21
7
All these answers are nice.
所有这些答案都很好。
But I cannot be sure that variable is a string, doesn't contains only spaces (this is important for me), and can contain '0' (string).
但是我不能确定变量是字符串,不包含空格(这对我来说很重要),并且可以包含“0”(字符串)。
My version:
我的版本:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Sample on jsfiddle.
jsfiddle样本。
#22
6
I usually use something like:
我通常用:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
#23
6
I did some research what happens if you pass a non-string and non-empty/null value to a tester function. As many knows, (0 == "") is true in javascript, but since 0 is a value and not empty or null, you may want to test for it.
我做了一些研究,如果您将一个非字符串和非空/空值传递给测试函数,会发生什么情况。正如许多人所知道的,(0 == ")在javascript中是正确的,但是由于0是一个值,而不是空的或空的,所以您可能想要测试它。
The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, boolean, objects, expressions etc.
以下两个函数只返回对未定义的、null、空/空格值和其他所有值的错误,如数字、布尔、对象、表达式等。
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:
更复杂的例子是存在的,但是这些例子很简单,并且给出了一致的结果。没有必要对未定义的进行测试,因为它包含在(value == null)检查中。您还可以通过将它们添加到字符串中来模拟c#行为:
String.IsNullOrEmpty = function (value) { ... }
You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:
您不希望将它放在字符串原型中,因为如果string类的实例为null,那么它将会出错:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error
I tested with the following value array. You can loop it through to test your functions if in doubt.
我使用以下值数组进行了测试。如果有疑问,可以通过循环来测试函数。
// 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; } }]
];
#24
6
to check if is exactly an empty string:
检查是否为空字符串:
if(val==="")...
to check if it is an empty string OR a a logical equivalent for no-value (null, undefined, 0, NaN, false, ...):
检查它是否是一个空字符串或一个逻辑等价的无值(null,未定义,0,NaN, false,…):
if(!val)...
#25
5
There's no isEmpty()
method, you have to check for the type and the length:
没有isEmpty()方法,您必须检查类型和长度:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test
is undefined
or null
.
当测试未定义或null时,需要类型检查以避免运行时错误。
#26
5
Try this
试试这个
str.value.length == 0
#27
4
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' />
this is also a generic way to check if field is empty.
这也是检查字段是否为空的通用方法。
#28
4
Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.
不要假设您检查的变量是字符串。不要假设这个var有一个长度,那么它就是一个字符串。
The thing is: think carefully about what your app must do and can accept. Build something robust.
问题是:仔细考虑你的应用必须做什么,并能接受。构建健壮的东西。
If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.
如果您的方法/函数只处理一个非空字符串,那么测试参数是否为非空字符串,并且不执行一些“技巧”。
As an example of something that will explode if you follow some advices here not carefully.
作为一个例子,如果你遵循一些建议将会爆炸,这里不小心。
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'
So, I'd stick with
所以,我坚持
if (myVar === '')
...
#29
3
You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution:
您也应该经常检查类型,因为JavaScript是鸭子类型的语言,所以您可能不知道什么时候以及如何在过程中间更改数据。所以,这里有一个更好的解决方案:
var str = "";
if (str === "") {
//...
}
#30
3
The underscore javascript library http://underscorejs.org/ provides a very useful _.isEmpty()
function for checking for empty strings and other empty objects.
下划线javascript库http://underscorejs.org/提供了一个非常有用的_.isEmpty()函数,用于检查空字符串和其他空对象。
Reference: http://underscorejs.org/#isEmpty
参考:http://underscorejs.org/ isEmpty
isEmpty
_.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.isEmpty _.isEmpty(对象)返回true,如果一个可枚举对象不包含值(没有可枚举的自属性)。对于字符串和类似数组的对象_。isEmpty检查长度属性是否为0。
_.isEmpty([1, 2, 3]);
=> false_。isEmpty([1,2,3]);= >假
_.isEmpty({});
=> true_.isEmpty({ });= > true
Other very useful underscore functions include:
http://underscorejs.org/#isNull _.isNull(object)
http://underscorejs.org/#isUndefined _.isUndefined(value)
http://underscorejs.org/#has _.has(object, key)
其他非常有用的下划线函数包括:http://underscorejs.org/#isNull _.isNull(对象)http://underscorejs.org/#isUndefined _.isUndefined(value) http://underscorejs.org/#有_。(对象,键)