Skip to content
Advertisement

Javascript Equivalent to PHP Explode()

I have this string:

0000000020C90037:TEMP:data

I need this string:

TEMP:data.

With PHP I would do this:

$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];

How do I effectively explode a string in JavaScript the way it works in PHP?

Advertisement

Answer

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'
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement