UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

105 lines (87 loc) 2.76 kB
--- layout: page title: "JavaScript substr_count function" comments: true sharing: true footer: true alias: - /functions/view/substr_count:559 - /functions/view/substr_count - /functions/view/559 - /functions/substr_count:559 - /functions/559 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's substr_count {% codeblock strings/substr_count.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/substr_count.js raw on github %} function substr_count (haystack, needle, offset, length) { // From: http://phpjs.org/functions // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + improved by: Brett Zamir (http://brett-zamir.me) // + improved by: Thomas // * example 1: substr_count('Kevin van Zonneveld', 'e'); // * returns 1: 3 // * example 2: substr_count('Kevin van Zonneveld', 'K', 1); // * returns 2: 0 // * example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10); // * returns 3: false var cnt = 0; haystack += ''; needle += ''; if (isNaN(offset)) { offset = 0; } if (isNaN(length)) { length = 0; } if (needle.length == 0) { return false; } offset--; while ((offset = haystack.indexOf(needle, offset + 1)) != -1) { if (length > 0 && (offset + needle.length) > length) { return false; } cnt++; } return cnt; } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/substr_count.js) Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure. Please also note that php.js offers community built functions and goes by the [McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/strings/substr_count.js) ### Example 1 This code {% codeblock lang:js example %} substr_count('Kevin van Zonneveld', 'e'); {% endcodeblock %} Should return {% codeblock lang:js returns %} 3 {% endcodeblock %} ### Example 2 This code {% codeblock lang:js example %} substr_count('Kevin van Zonneveld', 'K', 1); {% endcodeblock %} Should return {% codeblock lang:js returns %} 0 {% endcodeblock %} ### Example 3 This code {% codeblock lang:js example %} substr_count('Kevin van Zonneveld', 'Z', 0, 10); {% endcodeblock %} Should return {% codeblock lang:js returns %} false {% endcodeblock %} ### Other PHP functions in the strings extension {% render_partial _includes/custom/strings.html %}