String.prototype.count = function (str) { const reg = new RegExp('[^' + str + ']', 'g'); return this.replace(reg,'').length; } let str = 'abcd'; console.log(str.count('a'));