admin管理员组文章数量:1134037
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.
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.
Share Improve this question edited Aug 8, 2011 at 19:29 ckittel 6,6464 gold badges42 silver badges71 bronze badges asked Jan 8, 2010 at 22:06 patadpatad 9,66211 gold badges42 silver badges44 bronze badges 09 Answers
Reset to default 337Instead of checking the entire string to see if there's only whitespace, just check to see if there's at least one character of non whitespace:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
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
}
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 *
.
Well, if you are using jQuery, it's simpler.
if ($.trim(val).length === 0){
// string is invalid
}
Just check the string against this regex:
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');
I've used the following method to detect if a string contains only whitespace. It also matches empty strings.
if (/^\s*$/.test(myStr)) {
// the string contains only whitespace
}
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
}
This can be fast solution
return input < "\u0020" + 1;
本文标签:
版权声明:本文标题:javascript - How can I check if string contains characters & whitespace, not just whitespace? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736748973a1950933.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论