1

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
0

6 Answers 6

3

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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();

1 Comment

@Zeta -- Yep..just realized that :\
1

Pretty basic:

str.split(' ').length-1

jsFiddle example

Comments

1

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.