Ashima
Ashima

Reputation: 4834

Find number of spaces in a string using JavaScript

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

Answers (6)

pollirrata
pollirrata

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

Erez Pilosof
Erez Pilosof

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

Ashima
Ashima

Reputation: 4834

Actually, this works too.. Did not come to my mind before :P

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

Upvotes: 0

Matas Vaitkevicius
Matas Vaitkevicius

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

j08691
j08691

Reputation: 208032

Pretty basic:

str.split(' ').length-1

jsFiddle example

Upvotes: 1

tymeJV
tymeJV

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

Related Questions