Javascript String Prototype Count sub string

Description

Javascript String Prototype Count sub string


String.prototype.encodeRegExp = function() {
  return this.replace(/([*+-.?^${}()|[\]\/\\])/g, '\\$1');
}

String.prototype.getCount = function(str) {
  let regEx = new RegExp(str.encodeRegExp(), "g");
  return this.match(regEx).length;
}

console.log( "The quick brown fox jumped over the small frog.".getCount("e") ); // 4



PreviousNext

Related