One string method that I found today in Python is the count function to determine how many times a given substring appears in a string. Below is the equivalent of this function in JavaScript:

String.prototype.count = function(target, start, end) {
  start = start || 0;
  end = end == null ? this.length : end;
  return this.slice(start, end).split(target).length - 1;
};

It is important to note that if you pass a regular expression as the target instead of a string, an incorrect count may be returned. If you need this to work with regular expressions, you can use the following instead:

(function(toString) {
  String.prototype.count = function(target, start, end) {
    start = start || 0;
    end = end == null ? this.length : end;
    var me = this.slice(start, end);
    if (toString.call(target) == '[object RegExp]') {
      if (!target.global) {
        target = new RegExp(target.source,
          (target.ignoreCase ? 'i' : '')
          + (target.multiLine ? 'm' : '')
          + 'g');
      }
      var count = 0;
      me.replace(target, function() {
        count++;
      });
      return count;
    }
    return me.slice(start, end).split(target).length - 1;
  };
})({}.toString);

This function takes one required argument and two optional arguments. The required argument is the substring to be counted. The second argument is the starting point of the string to be searched. The third argument is the ending point of the string to be searched. If negative values are given as the starting or ending point, they will be calculated from the end of the string. Happy coding! 😎


Leave a Reply

Your email address will not be published. Required fields are marked *