Click to See Complete Forum and Search --> : Javascript, split function... php -> javascript conversion.


The-Master
12-30-2007, 08:42 AM
OK sorry about the confusing title but what I would like to do is split a bit of text like the following:

var1=hello&var2=world&foo=bar

into an array like the following

array['var1'] = hello;
array['var2'] = world;
array['foo'] = bar;

OK. There is a nice user created function in PHP to do this:

function explode_assoc($glue1, $glue2, $array)
{
$array2=explode($glue2, $array);
foreach($array2 as $val)
{
$pos=strpos($val,$glue1);
$key=substr($val,0,$pos);
$array3[$key] =substr($val,$pos+1,strlen($val));
}
return $array3;
}

But I can't seem to find one for javascript and I am very new with it so can't really change the above code into javascript.

If there is a way to do this in javascript of a way of making a custom function could you show me. Thanks very much. :)

dougal85
12-30-2007, 09:54 AM
// Converted function
function explode_assoc(glue1, glue2, array){
var array2 = array.split(glue2);
var array3 = [];
for(var x=0;x<array2.length;x++){
var tmp = array2[x].split(glue1);
array3[tmp[0]] = tmp[1];
}
return array3;
}

// Example usage
explode_assoc('=', '&', window.location.search.substring(1));


That should do it for you. I've done it in a slightly less efficient way. You may want to change the code inside the for loop to mimic that in the PHP codes look. ie, the substring rather than split.

The-Master
12-30-2007, 11:21 AM
Fantastic! Works perfectly! Thanks very much.

dougal85
12-30-2007, 11:25 AM
No problem. Remember to mark threads resolved.

bradgrafelman
12-30-2007, 02:45 PM
Also note that this could be done with a single function in PHP, parse_str(): parse_str($string, $array);