Reputation: 4834
How can I find out number of spaces in a string using JavaScript only?
"abc def rr tt" // should return 3
"34 45n v" // should return 2
Upvotes: 1
Views: 6965
Reputation: 5286
You can do it also with a regex
"abc def rr tt".match(/\s/g).length;
var x = "abc def rr tt".match(/\s/g).length;
alert(x);
x = "34 45n v".match(/\s/g).length;
alert(x);
Upvotes: 3
Reputation: 81
regex should be faster than split, but previous answers has an issue... when using match the return value can be undefined (no match/spaces) so use:
("abc def rr tt".match(/\s/g) || []).length; // 3
("abcdefrrtt".match(/\s/g) || []).length; // 0
Upvotes: 1
Reputation: 4834
Actually, this works too.. Did not come to my mind before :P
str.length - str.replace(/\s+/g, '').length;
Upvotes: 0
Reputation: 61529
This should do it.
It will split it on and will subtract one to account for
0
element.
("abc def rr tt".split(" ").length - 1)
Upvotes: 2
Reputation: 104795
Split on the spaces and get the length:
var length = "abc def rr tt".split(" ").length - 1;
Or write a nifty prototype function:
String.prototype.getWhitespaceCount = function() {
return this.split(" ").length - 1
}
var x = "abc def rr tt";
var length = x.getWhitespaceCount();
Upvotes: 1