2014-07-16 22 views

回答

0

其实,这工作太..没有来我的脑海前:P

str.length - str.replace(/\s+/g, '').length; 
1

的空间分割,并得到长度:

var length = "abc def rr tt".split(" ").length - 1; 

或者写一个漂亮的原型功能:

String.prototype.getWhitespaceCount = function() { 
    return this.split(" ").length - 1 
} 

var x = "abc def rr tt"; 
var length = x.getWhitespaceCount(); 
+1

备注做到这一点也:''ab“.split(”“).length === 2'。 – Zeta

+0

@Zeta - Yep..just意识到:\ – tymeJV

2

这应该这样做。 它会将它拆分为,并将扣除一个以计入0元素。

("abc def rr tt".split(" ").length - 1)