簡體   English   中英

如何檢查字符串是否包含字符和空格,而不僅僅是空格?

[英]How can I check if string contains characters & whitespace, not just whitespace?

檢查字符串是否僅包含空格的最佳方法是什么?

該字符串允許包含與空格組合的字符,但不僅僅是空格。

與其檢查整個字符串以查看是否只有空格,只需檢查是否至少有一個空格字符:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}

如果您的瀏覽器支持trim()函數,那么最簡單的答案

if (myString && !myString.trim()) {
    //First condition to check if string is not empty
    //Second condition checks if string contains just whitespace
}
if (/^\s+$/.test(myString))
{
      //string contains only whitespace
}

這會檢查 1 個或多個空白字符,如果您還匹配空字符串,則將+替換為*

好吧,如果您使用的是 jQuery,那就更簡單了。

if ($.trim(val).length === 0){
   // string is invalid
} 

只需根據此正則表達式檢查字符串:

if(mystring.match(/^\s+$/) === null) {
    alert("String is good");
} else {
    alert("String contains only whitespace");
}
if (!myString.replace(/^\s+|\s+$/g,""))
  alert('string is only whitespace');

當我想在字符串中間允許空格但不在開頭或結尾時,我最終使用的正則表達式是這樣的:

[\S]+(\s[\S]+)*

^[\S]+(\s[\S]+)*$

所以,我知道這是一個老問題,但你可以這樣做:

if (/^\s+$/.test(myString)) {
    //string contains characters and white spaces
}

或者你可以做nickf所說的並使用:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}

我使用以下方法來檢測字符串是否僅包含空格。 它還匹配空字符串。

if (/^\s*$/.test(myStr)) {
  // the string contains only whitespace
}

這可以是快速解決方案

return input < "\u0020" + 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM