Use PHP functions in JavaScript

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;
}
external links: original PHP docs | raw js source

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.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Kevin van Zonneveld
Sep 8th Permalink

q  @ Bjorn Roesbeke & Rafał Kukawski: Thanks for reporting & fixing the issue. Will be online shortly, but already fixed here: https://github.com/kvz/phpjs/commit/c83cf0d3bd5734444e5397af42b5f560240a9c54

Gravatar
Rafał Kukawski
Sep 5th Permalink

q  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;
}

Gravatar
Rafał Kukawski
Sep 5th Permalink

q  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;
 }

Gravatar
Bjorn Roesbeke
Sep 4th Permalink

q  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

Gravatar
nimatramon
Mar 31st Permalink

q  thanx man

Gravatar
Kevin van Zonneveld
25 Oct '09 Permalink

q  @ 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!

Gravatar
Theriault
18 Oct '09 Permalink

q  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')); 
}

Gravatar
Kevin van Zonneveld
15 Feb '09 Permalink

q  @ 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.

Gravatar
Brett Zamir
15 Feb '09 Permalink

q  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()...

Gravatar
tomasoma
14 Feb '09 Permalink

q  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("%"));
}

Gravatar
Kevin van Zonneveld
2 May '08 Permalink

q  @ Brett Zamir: I agree we should stick to PHP's implementation wherever we can. Thanks for your improvement!

Gravatar
Brett Zamir
30 Apr '08 Permalink

q  While the &quot;f_backwards&quot; 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=&quot;Javascript&quot;]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 &gt; 0){
var result = [];
while(f_string.length &gt; 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]


Contribute a New function