这是我的代码:
String.prototype.count = function(character) {
var seq = new RegExp('/'+character+'/g');
var matches = this.toString().match(seq);
return matches
};
'hello world'.count('o');
这就是它应该做的:
- 返回
o
数组
这就是它正在做的事情:
- 返回空
最佳答案
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:如果您不想在字符
中使用正则表达式 - 您应该转义它。
关于javascript - 编辑String的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26134870/