2012-05-10 30 views

回答

24

另一个好职位:Faster JavaScript Trim

你只需要申请trim功能,并检查字符串的长度。如果修剪后的长度为0 - 那么该字符串只包含空格。

var str = "data abc"; 
if((jQuery.trim(str)).length==0) 
    alert("only spaces"); 
else 
    alert("contains other characters"); 
+0

或者只是'!str.trim()' – Oriol

9
if (!input.match(/^\s*$/)) { 
    //your turn... 
} 
+0

这里假定'input'是值,而不是输入元素。 – Joseph

+0

是的,就像'var input =“dfdfd”',我猜,从实际输入获得输入值不是一个大问题。 –

+0

我更喜欢.trim()这个解决方案,因为您正在寻找特定的字符模式,这正是和明确的正则表达式描述的。这将需要一个读者多一点时间来理解你的修剪巧妙的技巧。 – Chris

0
if(!input.match(/^([\s\t\r\n]*)$/)) { 
    blah.blah(); 
} 
2

或者,可以做一个test()返回boolean不是数组

//assuming input is the string to test 
if(/^\s*$/.test(input)){ 
    //has spaces 
} 
0

最快溶液使用正则表达式原型函数test()和寻找任何字符那不是空格或换行符\S

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

如果您有超长的字符串,它可以产生显着的差异。

相关问题