10

I have a string "John Doe's iPhone6"

Visually, I know that it contains 2 spaces.

How do I count spaces in a string in javascript ?

I've tried

var input = this.value;
// console.log(input.count(' '));
Community
  • 1
  • 1
code-8
  • 54,650
  • 106
  • 352
  • 604

3 Answers3

31

Try this

var my_string = "John Doe's iPhone6";
var spaceCount = (my_string.split(" ").length - 1);
console.log(spaceCount)
Mike
  • 737
  • 1
  • 7
  • 11
11

Use RegExp:

"John Doe's iPhone6".match(/([\s]+)/g).length
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
elad.chen
  • 2,375
  • 5
  • 25
  • 37
  • 1
    This method will be failed if your string like this "%20%20%20%20%20%20%20%20%20%20%20%20%20% ------------by some one" %20 is space since stackoverflow won't show each the space – Ethan Yan Sep 11 '18 at 23:42
  • This will also fail if there are no spaces, because match will return `null`. Best to check for null before getting the .length – fallerd Sep 21 '22 at 22:13
9

Use split and count them less 1 (-1):

var string = "John Doe's iPhone6";
string.split(" ").length-1
Alvaro Silvino
  • 9,441
  • 12
  • 52
  • 80