0

I have recently started learning coding and am trying to learn how to create functions but I am finding it quite difficult.

How would write a function called countDots(x) that takes a string as an argument and returns the number of dots (.) it contains.E.g. x = "www.google.com" the function will return with 2.

Chris Hapeshis
  • 83
  • 1
  • 11
  • 6
    `E.g. x = "www.google.com" the function will return with 3.` Why 3, it should be `2` – Tushar Aug 24 '15 at 11:29
  • 5
    possible duplicate of [Count the number of occurences of a character in a string in Javascript](http://stackoverflow.com/questions/881085/count-the-number-of-occurences-of-a-character-in-a-string-in-javascript) – DavidDomain Aug 24 '15 at 11:30
  • sorry that is what i meant haha – Chris Hapeshis Aug 24 '15 at 11:30

3 Answers3

4

I would do it this way:

function dotCounter(x) {
    return x.split('.').length -1;
}

document.write( dotCounter("www.google.com") );
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
0

Please try this

function countDots(x){
    return((x.match(/\./g) || []).length)
}
Rino Raj
  • 6,264
  • 2
  • 27
  • 42
  • @Rino Raj, thank you for that. Is it possible for you to explain to me what each part means, I know the first line is naming the function countDots(x). But what does each part of the second line mean? – Chris Hapeshis Aug 24 '15 at 11:43
  • 1
    @ChrisHapeshis * x is the argument. * The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object. .. * next is using regex the number of "." is calculated ang its length is found out – Rino Raj Aug 24 '15 at 12:25
0

As you say you're learning to code at the moment, you don't need speed-optimised code. I'd suggest this - it only use ideas that turn up in almost all programming languages:

function countDots(str) {
  var count = 0;
  for (var x = 0; x < str.length; x++) {
    if str.charAt(x) == '.' {
      count++;
    }
  }
  return count;
}

You can worry about speed once you're happy that you've got the basics! Good luck

randomsimon
  • 471
  • 4
  • 11