Skip to content

Commit 04d0c07

Browse files
committed
I created this new explode function, which fixes several bugs that I found in the previous version. Note: sorry for any english mistakes, english is not my first language. I also posted this function in http://phpjs.org/functions/explode:396#comment_153595
1 parent 0f7c76a commit 04d0c07

File tree

1 file changed

+29
-38
lines changed

1 file changed

+29
-38
lines changed

functions/strings/explode.js

Lines changed: 29 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,33 @@
11
function explode (delimiter, string, limit) {
2-
// http://kevin.vanzonneveld.net
3-
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
4-
// + improved by: kenneth
5-
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
6-
// + improved by: d3x
7-
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
8-
// * example 1: explode(' ', 'Kevin van Zonneveld');
9-
// * returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
10-
// * example 2: explode('=', 'a=bc=d', 2);
11-
// * returns 2: ['a', 'bc=d']
12-
var emptyArray = {
13-
0: ''
14-
};
152

16-
// third argument is not required
17-
if (arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined') {
18-
return null;
19-
}
3+
if ( arguments.length < 2 || typeof delimiter == 'undefined' || typeof string == 'undefined' ) return null;
4+
if ( delimiter === '' || delimiter === false || delimiter === null) return false;
5+
if ( typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object'){
6+
return { 0: '' };
7+
}
8+
if ( delimiter === true ) delimiter = '1';
9+
10+
// Here we go...
11+
delimiter += '';
12+
string += '';
13+
14+
var s = string.split( delimiter );
15+
2016

21-
if (delimiter === '' || delimiter === false || delimiter === null) {
22-
return false;
23-
}
17+
if ( typeof limit === 'undefined' ) return s;
18+
19+
// Support for limit
20+
if ( limit === 0 ) limit = 1;
21+
22+
// Positive limit
23+
if ( limit > 0 ){
24+
if ( limit >= s.length ) return s;
25+
return s.slice( 0, limit - 1 ).concat( [ s.slice( limit - 1 ).join( delimiter ) ] );
26+
}
2427

25-
if (typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {
26-
return emptyArray;
27-
}
28-
29-
if (delimiter === true) {
30-
delimiter = '1';
31-
}
32-
33-
if (!limit) {
34-
return string.toString().split(delimiter.toString());
35-
}
36-
// support for limit argument
37-
var splitted = string.toString().split(delimiter.toString());
38-
var partA = splitted.splice(0, limit - 1);
39-
var partB = splitted.join(delimiter.toString());
40-
partA.push(partB);
41-
return partA;
42-
}
28+
// Negative limit
29+
if ( -limit >= s.length ) return [];
30+
31+
s.splice( s.length + limit );
32+
return s;
33+
}

0 commit comments

Comments
 (0)