检查字符串是否只包含空格的最佳方法是什么?
字符串允许包含带有空格的字符 合并,但不允许包含带有空格的字符 只是。
只需检查字符串与正则表达式的对应关系:
if(mystring.match(/^\s+$/) === null) { alert("String is good"); } else { alert("String contains only whitespace"); }
if (/^\s+$/.test(myString)) { //string contains only whitespace }
这将检查1个或多个空格字符,如果它也匹配一个空字符串,那么将 +替换为 *。
+
*
if (!myString.replace(/^\s+|\s+$/g,"")) alert('string is only whitespace');
不要检查整个字符串是否只有空格,只要检查 不空格中是否至少有一个字符:
if (/\S/.test(myString)) { // string is not empty and not just whitespace }
当我想在字符串的中间留空格但不在开头或结尾处留空格时,我最后使用的正则表达式是:
[\S]+(\s[\S]+)*
或者
^[\S]+(\s[\S]+)*$
我知道这是个老问题,但你可以这样做:
if (/^\s+$/.test(myString)) { //string contains characters and white spaces }
或者你可以按 Nick说的做,使用:
如果您使用的是 jQuery,那么它更简单。
if ($.trim(val).length === 0){ // string is invalid }
如果您的浏览器支持 trim()函数,这是最简单的答案
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(myStr)) { // the string contains only whitespace }
这是一个快速的解决方案
return input < "\u0020" + 1;