Reputation: 1749
For basic use, these functions work the same. Split an input string into an array based on an extra string. Both also take an extra "limit" variable.
However, in PHP, the limit means that after you've matched limit items, the entire rest of the string does into the last item of the array. This is actually quite useful.
JS's limit means that once your return array has limit many items, it just stops adding items to it. This implementation of limit is kind of useless, and also easily emulated with other array functions.
So is there an easy way to emulate PHP's way with JS?
Consider the following as the input string:
$str = "7,43,This is a long sentence, know what I mean?";
I'd want $str.split(",",3);
to return this array:
{"7","43","This is a long sentence, know what I mean?"}
Upvotes: 0
Views: 276
Reputation: 147216
Something like this, using String.split
, Array.slice
, Array.concat
and Array.join
should do what you want:
function explode(char, str, limit) {
let a = str.split(char);
return a.slice(0, limit-1).concat(a.slice(limit-1).join(char));
}
let str = "7,43,This is a long sentence, know what I mean?";
console.log(explode(',', str, 3));
Upvotes: 3
Reputation: 17626
Using String#split, Array#splice, Array#join, and spread operator.
const s = "7,43,This is a long sentence, know what I mean?"
function explode(delimiter, str, limit) {
const data = str.split(delimiter);
return [...data.splice(0, limit - 1), data.join(delimiter)];
}
const res = explode(',', s, 3);
console.log(res);
Upvotes: 4