Split in javascript

In JavaScript, split behaves a litte different than expected. For example, we have a string needed to be split into pieces:

1
2
var str = 'Steve Jobs, Deciding what not to do is, ' +
'as important as deciding what to do';

Say, we need to split and format the above string into:

1
Steve Jobs: Deciding what not to do is, as important as deciding what to do.

If we use split without limitation:

1
2
var pieces = str.split(',');
console.log(pieces);

Actually, we got:

1
[Steve Jobs, Deciding what not to do is, as important as deciding what to do]`.

So we add another argument:

1
2
var pieces = str.split(',', 1);
console.log(pieces);

Got Only [Steve Jobs]. The result is not we except. The second argument just identify how many elments in the spilt pieces would return.

So we need to do the split ourself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function splitEnhanced(str, seperator, maxSplit) {
var pieces = str.split(seperator);
var result = [];
if (!maxSplit) {
return pieces;
}
while (maxSplit > 0) {
result.push(pieces.shift());
maxSplit--;
}
result.push(pieces.join(seperator));
return result;
}
var pieces = splitEnhanced(str, ',', 1);
console.log(pieces.join(':'));
0%