Skip to content

Instantly share code, notes, and snippets.

@masautt
Created September 6, 2019 16:22
Show Gist options
  • Save masautt/65167ff69e94f2fc01b3a49b1d7ec846 to your computer and use it in GitHub Desktop.
Save masautt/65167ff69e94f2fc01b3a49b1d7ec846 to your computer and use it in GitHub Desktop.
How to count number of occurrences of a substring in JavaScript?
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
console.log("Marek Sautter".count("e")); // --> 2
console.log("I got a letter from Marek Sautter".count("tt")); // --> 2
// https://stackoverflow.com/questions/881085/count-the-number-of-occurrences-of-a-character-in-a-string-in-javascript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment