How can I check if string contains characters & wh

2019-01-12 18:54发布

What is the best way to check if a string contains only whitespace?

The string is allowed to contain characters combined with whitespace, but not just whitespace.

7条回答
霸刀☆藐视天下
2楼-- · 2019-01-12 19:20

Simplest answer if your browser supports the trim() function

if (myString && !myString.trim()) {
    //First condition to check if string is not empty
    //Second condition checks if string contains just whitespace
}
查看更多
欢心
3楼-- · 2019-01-12 19:31
if (!myString.replace(/^\s+|\s+$/g,""))
  alert('string is only whitespace');
查看更多
▲ chillily
4楼-- · 2019-01-12 19:32

The regular expression I ended up using for when I want to allow spaces in the middle of my string, but not at the beginning or end was this:

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

or

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

So, I know this is an old question, but you could do something like:

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

or you can do what nickf said and use:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}
查看更多
We Are One
5楼-- · 2019-01-12 19:34

Well, if you are using jQuery, it's simpler.

if ($.trim(val).length === 0){
   // string is invalid
} 
查看更多
在下西门庆
6楼-- · 2019-01-12 19:39
if (/^\s+$/.test(myString))
{
      //string contains only whitespace
}

this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.

查看更多
神经病院院长
7楼-- · 2019-01-12 19:44

Just check the string against this regex:

if(mystring.match(/^\s+$/) === null) {
    alert("String is good");
} else {
    alert("String contains only whitespace");
}
查看更多
登录 后发表回答