l008com
l008com

Reputation: 1749

Emulate PHP's explode( ) with Javascript's .split( )

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

Answers (2)

Nick
Nick

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

kockburn
kockburn

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

Related Questions