Nodejs String Count Char countOf(char)

Here you can find the source of countOf(char)

Method Source Code

var fs = require('fs');

// Define a function for counting the number of instances of a char in a string
String.prototype.countOf = function(char) {
   return this.split(char).length - 1;
}

if (process.argv.length >= 3) {
   var buffer = fs.readFileSync(process.argv[2]);
   // We need to find the total amount of newline characters in the buffer
   // First, convert the buffer to string
   var str = buffer.toString();
   // Use our function above to count the number of newlines
   var count = str.countOf('\n');
   // print to stdout
   console.log(count);// ww w .  ja  v a  2  s  .  c  o  m
}

Related

  1. countChars(c)
    String.prototype.countChars = function(c) {
      var cpt = 0;
      for(var i=0;i<this.length;i++) {
        if(this.charAt(i)==c) cpt++;
      return cpt;
    var monTexte = "Je s uis un texte";
    console.log(monTexte.countChars(' '));
    ...
    
  2. countOf(char)
    var fs = require('fs');
    String.prototype.countOf = function(char) {
      return this.split(char).length - 1;
    fs.readFile(process.argv[2], 'utf8', function(err, data) {
      if (err) {
        console.error(err);
        return;
      var lines = data.countOf('\n');
      console.log(lines);
    });
    
  3. countWords()
    String.prototype.countWords = function(){
      return this.split(/\s+/).length;
    'olly olly in come free'.countWords();