Created
September 6, 2019 16:22
-
-
Save masautt/65167ff69e94f2fc01b3a49b1d7ec846 to your computer and use it in GitHub Desktop.
How to count number of occurrences of a substring in JavaScript?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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