Javascript Equivalent to PHP Explode() Javascript Equivalent to PHP Explode() php php

Javascript Equivalent to PHP Explode()


This is a direct conversion from your PHP code:

//Loading the variablevar mystr = '0000000020C90037:TEMP:data';//Splitting it with : as the separatorvar myarr = mystr.split(":");//Then read the values from the array where 0 is the first//Since we skipped the first element in the array, we start at 1var myvar = myarr[1] + ":" + myarr[2];// Show the resulting valueconsole.log(myvar);// 'TEMP:data'


You don't need to split. You can use indexOf and substr:

str = str.substr(str.indexOf(':')+1);

But the equivalent to explode would be split.


String.prototype.explode = function (separator, limit){    const array = this.split(separator);    if (limit !== undefined && array.length >= limit)    {        array.push(array.splice(limit - 1).join(separator));    }    return array;};

Should mimic PHP's explode() function exactly.

'a'.explode('.', 2); // ['a']'a.b'.explode('.', 2); // ['a', 'b']'a.b.c'.explode('.', 2); // ['a', 'b.c']