phpjs
Version:
77 lines (62 loc) • 2.3 kB
Markdown
layout: page
title: "JavaScript chunk_split function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/chunk_split:369
- /functions/view/chunk_split
- /functions/view/369
- /functions/chunk_split:369
- /functions/369
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's chunk_split
{% codeblock strings/chunk_split.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/chunk_split.js raw on github %}
function chunk_split (body, chunklen, end) {
// From: http://phpjs.org/functions
// + original by: Paulo Freitas
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Theriault
// * example 1: chunk_split('Hello world!', 1, '*');
// * returns 1: 'H*e*l*l*o* *w*o*r*l*d*!*'
// * example 2: chunk_split('Hello world!', 10, '*');
// * returns 2: 'Hello worl*d!*'
chunklen = parseInt(chunklen, 10) || 76;
end = end || '\r\n';
if (chunklen < 1) {
return false;
}
return body.match(new RegExp(".{0," + chunklen + "}", "g")).join(end);
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/chunk_split.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/chunk_split.js)
### Example 1
This code
{% codeblock lang:js example %}
chunk_split('Hello world!', 1, '*');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
'H*e*l*l*o* *w*o*r*l*d*!*'
{% endcodeblock %}
### Example 2
This code
{% codeblock lang:js example %}
chunk_split('Hello world!', 10, '*');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
'Hello worl*d!*'
{% endcodeblock %}
### Other PHP functions in the strings extension
{% render_partial _includes/custom/strings.html %}