包含一个空格的字符串长度始终等于1:
alert('My str length: ' + str.length);
Run Code Online (Sandbox Code Playgroud)
空间是一个角色,所以:
str = " ";
alert('My str length:' + str.length); // My str length: 3
Run Code Online (Sandbox Code Playgroud)
如何区分空字符串和仅包含空格的字符串?如何检测仅包含空格的字符串?
Ror*_*san 108
要实现此目的,您可以使用正则表达式删除字符串中的所有空格.如果结果字符串的长度是0
,那么您可以确定原始字符仅包含空格.试试这个:
var str = " ";
if (!str.replace(/\s/g, '').length) {
console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');
}
Run Code Online (Sandbox Code Playgroud)
pmr*_*ule 35
最快的解决方案是使用正则表达式原型函数test()并查找不是空格或换行符的任何字符\S
:
if (/\S/.test(str))
{
// found something other than a space or line break
}
Run Code Online (Sandbox Code Playgroud)
如果你有一个超长字符串,它可以产生显着的差异.
bob*_*603 31
与 Rory 的回答类似,使用 ECMA 5,您现在可以只调用str.trim().length
而不是使用正则表达式。如果结果值为 0,您就知道您有一个仅包含空格的字符串。
if (!str.trim().length) {
console.log('str is empty!');
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关修剪的更多信息。
编辑:几年后看了这个之后,我注意到这可以进一步简化。由于修剪的结果将是真值或假值,您还可以执行以下操作:
if (!str.trim()) {
console.log('str is empty!');
}
Run Code Online (Sandbox Code Playgroud)
hev*_*ev1 23
if(!str.trim()){
console.log('string is empty or only contains spaces');
}
Run Code Online (Sandbox Code Playgroud)
String#trim()
删除字符串开头和结尾的空格。如果字符串只包含空格,则修剪后为空,空字符串在 JavaScript 中为 false。
如果字符串可能是null
或undefined
,我们需要在修剪之前首先检查字符串本身是否为假。
if(!str || !str.trim()){
//str is null, undefined, or contains only spaces
}
Run Code Online (Sandbox Code Playgroud)
这可以使用可选的链接运算符来简化。
if(!str?.trim()){
//str is null, undefined, or contains only spaces
}
Run Code Online (Sandbox Code Playgroud)
您可以通过为字符串创建修剪函数来修剪字符串值。
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
Run Code Online (Sandbox Code Playgroud)
现在它将对您的每个String可用,您可以将其用作
str.trim().length// Result will be 0
Run Code Online (Sandbox Code Playgroud)
您也可以使用此方法删除String开头和结尾处的空格,即
" hello ".trim(); // Result will be "hello"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
72377 次 |
最近记录: |