Page 1 of 1

Split url in JavaScript

Posted: Wed Feb 28, 2007 7:29 am
by WaldoMonster
What I came up with so far is:

Code: Select all

var parts = url.split('?');
url = parts[0];
query = parts[1];
This is working perfect except when there is a question mark in the url like:

Code: Select all

var url = 'javascript.php?action=list&name=Do you know?';
As you can see the url is not yet encoded and therefore there can be more question marks in it.
Is there a solution to split the url by the first question mark?

Posted: Wed Feb 28, 2007 7:37 am
by kaszu
http://www.quirksmode.org/js/strings.html#indexof
http://www.quirksmode.org/js/strings.html#substring

Code: Select all

var occurance = url.indexOf('?');
var part1 = '';
var part2 = '';

if (occurance > -1)
{
    part1 = url.subString(0, occurance);
    part2 = url.subString(occurance);
}else{
    part1  = url;
}
Untested!

Posted: Wed Feb 28, 2007 7:45 am
by WaldoMonster
That was fast.
Thanks very much kaszu.

Posted: Wed Feb 28, 2007 8:02 am
by WaldoMonster
I did made a minor change to get it to work:

Code: Select all

var occurance = url.indexOf('?'); 
var part1 = ''; 
var part2 = ''; 

if (occurance > -1) 
{ 
    part1 = url.substring(0, occurance); 
    part2 = url.substring(occurance + 1); 
}else{ 
    part1  = url; 
}