count.js 399 B

123456789101112131415
  1. "use strict";
  2. var ensureString = require("../../object/validate-stringifiable-value");
  3. module.exports = function (search) {
  4. var string = ensureString(this), count = 0, index = 0;
  5. search = ensureString(search);
  6. if (!search) throw new TypeError("Search string cannot be empty");
  7. while ((index = string.indexOf(search, index)) !== -1) {
  8. ++count;
  9. index += search.length;
  10. }
  11. return count;
  12. };