Reputation: 1801
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');
o
sUpvotes: 0
Views: 43
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
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