Javascript Equivalent to PHP Explode()

Javascript Equivalent to PHP Explode()

I have a string that looks like this:

0000000020C90037:TEMP:data

And I need to grab everything after the first colon, so that I have TEMP:data.
I don’t often work in Javascript, if it were PHP I would do this:
$str = ‘0000000020C90037:TEMP:data’;
$arr = explode(“:”, $str);
$var = $arr[1].”:”.$arr[2];

Solutions/Answers:

Solution 1:

This is a direct conversion from your PHP code:

//Loading the variable
var mystr = '0000000020C90037:TEMP:data';

//Splitting it with : as the separator
var 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 1
var myvar = myarr[1] + ":" + myarr[2];

// Show the resulting value
console.log(myvar);
// 'TEMP:data'

Solution 2:

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.

Solution 3:

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']

Solution 4:

Looks like you want split

Solution 5:

Try this:

arr = str.split (":");

Solution 6:

create’s an object :

// create a data object to store the information below.
    var data   = new Object();
// this could be a suffix of a url string. 
    var string = "?id=5&first=John&last=Doe";
// this will now loop through the string and pull out key value pairs seperated 
// by the & character as a combined string, in addition it passes up the ? mark
    var pairs = string.substring(string.indexOf('?')+1).split('&');
    for(var key in pairs)
    {
        var value = pairs[key].split("=");
        data[value[0]] = value[1];
    }

// creates this object 
    var data = {"id":"5", "first":"John", "last":"Doe"};

// you can then access the data like this
    data.id    = "5";
    data.first = "John";
    data.last  = "Doe";