0

This is my code:

String.prototype.count = function(character) {
    var seq = new RegExp('/'+character+'/g');
    var matches = this.toString().match(seq);
    return matches
};

'hello world'.count('o');

This is what it should do:

  • Return array of os

This is what it's doing:

  • Return null
Pixeladed
  • 1,773
  • 5
  • 14
  • 26
  • 1
    That's not how you create regex with the RegExp constructor, check the docs here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp – elclanrs Oct 01 '14 at 05:49
  • possible duplicate of [How to count string occurrence in string?](http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string) – Phil Oct 01 '14 at 05:53
  • Also, your method is named very poorly. I would expect a method named `count` to return a single integer. – Phil Oct 01 '14 at 05:55

2 Answers2

1
String.prototype.count = function(character) {
    var seq = new RegExp(character, 'g');
    var matches = this.toString().match(seq);
    return matches;
};

alert('hello world'.count('o'));

ps: if you do not want to use regexps in character - you should escape it.

Cheery
  • 16,063
  • 42
  • 57
0

You're not creating the RegExp that you want. It should be:

    var seq = new RegExp(character, 'g');

When you use the RegExp constructor, you just give it the contents of the regular expression, you don't need the / delimiters -- those are only used in RegExp literals. Your RegExp is looking for the literal string /o/g.

Barmar
  • 741,623
  • 53
  • 500
  • 612