JavaScript str_split
Convert a string to an array. If split_length is specified, break the string down into chunks each split_length characters long.
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 | function str_split (string, split_length) { // Convert a string to an array. If split_length is specified, break the string down into chunks each split_length characters long. // // version: 1009.820 // discuss at: http://phpjs.org/functions/str_split // + original by: Martijn Wieringa // + improved by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Onno Marsman // + revised by: Theriault // + input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/) // + revised by: Rafał Kukawski (http://blog.kukawski.pl/) // * example 1: str_split('Hello Friend', 3); // * returns 1: ['Hel', 'lo ', 'Fri', 'end'] if (split_length === null) { split_length = 1; } if (string === null || split_length < 1) { return false; } string += ''; var chunks = [], pos = 0, len = string.length; while (pos < len) { chunks.push(string.slice(pos, pos += split_length)); } return chunks; } |
Examples
Running
1 | str_split('Hello Friend', 3); |
Should return
1 | ['Hel', 'lo ', 'Fri', 'end'] |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have str_split goodness in JavaScript.
split_length should be optional
function str_split(string, split_length) {
if(split_length == null){
split_length = 1;
}
if (string == null || split_length < 1) {
return false;
}
string += '';
var chunks = [], pos = 0, len = string.length;
while(pos < len){
chunks.push(string.slice(pos, pos += split_length));
}
return chunks;
}
The problem is, that IE adds some properties to the result array (input, index, lastIndex) and count() also counts them.
Beside that, str_split won't work for multiline strings.
Below another approach to this problem
function str_split(string, split_length) {
if (string == null || split_length < 1) {
return false;
}
string += '';
var chunks = [], pos = 0, len = string.length;
while(pos < len){
chunks.push(string.slice(pos, pos += split_length));
}
return chunks;
}
There's something wrong with this function but due to a lack of Javascript knowledge i can only provide the testcase.
I split a string:
http://shared.bjornroesbeke.be/phpjs/count_splitted_test.php
And when i count the number of items the results differ:
http://shared.bjornroesbeke.be/phpjs/count_splitted_result.png
Note that count() seems to function properly:
http://shared.bjornroesbeke.be/phpjs/count_regular_test.php
@ Theriault: As always, brilliant stuff man! I've added your code. Proof:
http://github.com/kvz/phpjs/commit/718895323939ff5e0f674a537e9a4546fce71c6e ; )
Will be online here shortly as well!
Here's a shorter version that runs faster than the current one.
function str_split(s, l) {
if (s == undefined || !s.toString || l < 1) {
return false;
}
return s.toString().match(new RegExp('.{1,' + (l || '1') + '}', 'g'));
}
@ tomasoma: You could also look at the explode() function. It's based on JavaScript's own .split() function, but adds support for PHP's arguments: limit.
Maybe I'm not getting you right though: Feel free to point out something I'm missing here.
Hello and bonjour tomasoma,
Thanks for sharing. Kevin likes to stick with the default PHP behavior in functions here, but I presume he won't mind a useful tip here.
However, I'm not clear though why you felt you needed to add a split function which JavaScript already has? Is it fixing bug in some browser? In Firefox I get the same behavior with your function as with JS split()...
I'm a novice sorry my comments are in french hehehe
I just needed the "real" split function which return a table from a string divide by a specified character : here is a new method for the string object :
good web site great ideas !!! thanks !!! ;-)
// le split sur un caractère qui retourne un tableau
// bug peut-être si le caractère recherché est présent à l'index 0
function split(car){
var tab = new Array();
var deb;
var fin=0;
var i=0;
var test;
while(test!=-1){
deb=fin;
fin=this.indexOf(car,deb+1);
test=fin;
if(fin==-1){fin=this.length;}
if(deb!=0){deb++;}
tab[i]=this.substring(deb,fin);
i++;
}
// alert(tab);
return tab;
}
String.prototype.split = split;
function test(){
var text="toma%soma%c'est cool on test tout%76898644";
alert(text.split("%"));
}
@ Brett Zamir: I agree we should stick to PHP's implementation wherever we can. Thanks for your improvement!
While the "f_backwards" argument might not do any harm, I prefer not to add distinctions not present in PHP, if for nothing else than if PHP changes later (of course it can be ignored here for now, but...)
However, one additional change in my own version below which I added and think yours should to is to allow a default of 1 for length (as in PHP):
[CODE="Javascript"]function str_split ( f_string, f_split_length){
// http://kevin.vanzonneveld.net
// + original by: Martijn Wieringa
// * example 1: str_split('Hello Friend', 3);
// * returns 1: ['Hel', 'lo ', 'Fri', 'end']
if (f_split_length == undefined) {
f_split_length = 1;
}
if(f_split_length > 0){
var result = [];
while(f_string.length > f_split_length) {
result[result.length] = f_string.substring(0, f_split_length);
f_string = f_string.substring(f_split_length);
}
result[result.length] = f_string;
return result;
}
return false;
}[/CODE]


Kevin van Zonneveld
Sep 8th