Skip to content

Instantly share code, notes, and snippets.

@djom202
Last active April 4, 2018 14:44
Show Gist options
  • Save djom202/7d97bddcf5ea7d7fcd0a4d59e6db357b to your computer and use it in GitHub Desktop.
Save djom202/7d97bddcf5ea7d7fcd0a4d59e6db357b to your computer and use it in GitHub Desktop.
The function will count the amount of existences of a character specific into the string
// You'll need to include the prototypes.js file before use it.
// To NodeJs: let proto = require('prototypes');
// To Html: <script src="path/prototypes.js"></script>
// Note: ChanceJs plugin could be omited since it's only used to verify the correct working for any case.
let Chance = require('chance'); // Plugin to generate content random
let chance = new Chance();
let text = chance.paragraph(); // Generating paragraph random
let char = chance.character(); // Generating character random
let result = text.count(char);
console.log('char', char);
console.log('result', result);
if (!Array.prototype.count) {
String.prototype.count = function (toSearch) {
if (toSearch == null) throw new TypeError("Array.prototype.count() - can't be null the search parameter");
var str = this,
r = 0,
idx = 0;
do {
idx = str.indexOf(toSearch) + 1;
if(idx != 0){
r++;
str = str.slice(idx, str.length);
}
}while(idx != 0);
return r;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment