Javascript 如何检测仅包含空格的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10261986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:33:17  来源:igfitidea点击:

How to detect string which contains only spaces?

javascript

提问by Luca

A string length which contains one space is always equal to 1:

包含一个空格的字符串长度总是等于 1:

alert('My str length: ' + str.length);

The space is a character, so:

空格是一个字符,所以:

str = "   ";
alert('My str length:' + str.length); // My str length: 3

How can I make a distinction between an empty string and a string which contains only spaces? How can I detect a string which contain only spaces?

如何区分空字符串和仅包含空格的字符串?如何检测仅包含空格的字符串?

回答by Rory McCrossan

To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0, then you can be sure the original only contained whitespace. Try this:

为此,您可以使用正则表达式删除字符串中的所有空格。如果结果字符串的长度为0,则可以确定原始字符串仅包含空格。尝试这个:

var str = "    ";
if (!str.replace(/\s/g, '').length) {
  console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');
}

回答by pmrotule

The fastest solution would be using the regex prototype function test()and looking for any character that is not a space or line break \S:

最快的解决方案是使用正则表达式原型函数test()并查找不是空格或换行符的任何字符\S

if (/\S/.test(str))
{
    // found something other than a space or line break
}

In case you have a super long string, it can make a significant difference.

如果你有一个超长的字符串,它会产生很大的不同。

回答by Shehzad

You can Trim your String value by creating a trim function for your Strings.

您可以通过为字符串创建修剪函数来修剪字符串值。

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

now it will be available for your every String and you can use it as

现在它将可用于您的每个字符串,您可以将其用作

str.trim().length// Result will be 0

You can also use this method to remove the white spaces at the start and end of the String i.e

您也可以使用此方法去除字符串开头和结尾处的空格,即

"  hello  ".trim(); // Result will be "hello"

回答by hev1

Removing the whitespace from a String can be done using String.trim().

可以使用String.trim().

//!str will return true if the string is null, undefined, or ''
//!str.trim() will return true if the string is '' after removing trailing whitespaces (which means it is an empty string)
function isNullOrEmpty(str){
    return !str||!str.trim();
}

This method can be used to check if a String contains only spaces and it can be invoked every time like this:

此方法可用于检查 String 是否仅包含空格,并且每次都可以像这样调用它:

var str = document.getElementById("txt").value;
if(isNullOrEmpty(str)){
     console.log("String is empty or contains only spaces.");
}

Demo:

演示:

function isNullOrEmpty(str){
    return !str||!str.trim();
}
const resultElem = document.getElementById("result");
const inputElem = document.querySelector('input');
function testEmpty(){
  if(isNullOrEmpty(inputElem.value)){
  result.textContent = "Input is an empty String or a String containing only spaces.";
  } else {
    result.textContent = "Input is not an empty String or a String containing only spaces.";
  }
}
<input type="text">
<br/>
<button onClick="testEmpty()">Check</button>
<p/>
<span id="result"></span>

回答by bobbyg603

Similar to Rory's answer, with ECMA 5 you can now just call str.trim().length instead of using a regular expression. If the resulting value is 0 you know you have a string that contains only spaces.

与 Rory 的回答类似,使用 ECMA 5,您现在可以只调用 str.trim().length 而不是使用正则表达式。如果结果值为 0,您就知道您有一个仅包含空格的字符串。

if (!str.trim().length) {
    console.log("str is empty!");
}

You can read more about trim here.

您可以在此处阅读有关修剪的更多信息。

回答by user3024615

Trim your String value by creating a trim function

通过创建修剪函数修剪你的字符串值

var text = "  ";
if($.trim(text.length == 0){
  console.log("Text is empty");
}
else
{
  console.log("Text is not empty");
}