Pixeladed
Pixeladed

Reputation: 1801

Editing prototype of String

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:

This is what it's doing:

Upvotes: 0

Views: 43

Answers (2)

Barmar
Barmar

Reputation: 780869

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.

Upvotes: 0

Cheery
Cheery

Reputation: 16214

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.

Upvotes: 1

Related Questions