7

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
  • 49,286
  • 91
  • 294
  • 502

3 Answers3

29

Try this

var my_string = "John Doe's iPhone6";
var spaceCount = (my_string.split(" ").length - 1);
console.log(spaceCount)
Mayki Nayki
  • 717
  • 1
  • 7
  • 11
10

Use RegExp:

"John Doe's iPhone6".match(/([\s]+)/g).length
James Thorpe
  • 29,949
  • 5
  • 70
  • 88
elad.chen
  • 2,277
  • 5
  • 23
  • 33
  • 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
9

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

var string = "John Doe's iPhone6";
string.split(" ").length-1
Alvaro Silvino
  • 8,773
  • 11
  • 48
  • 77