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
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: 911.718
    // 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
    // *         example 1: str_split('Hello Friend', 3);    // *         returns 1: ['Hel', 'lo ', 'Fri', 'end']
    if (string === undefined || !string.toString || split_length < 1) {
        return false;
    }
    return string.toString().match(new RegExp('.{1,' + (split_length || '1') + '}', 'g'));}
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
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.

1
2
3
4
56
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 !!! ;-)

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
//      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 "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):

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
20
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;
}


Contribute a New function