Helping ordinary people create extraordinary websites!
   

How to get the current URL and split it with JavaScript?

Friday, 6th November 2009
by shawnlevin

I'm trying to figure out how to create a JS that will automatically obtain the URL of the page from which the form is submitting, then parse that URL into two separate variables

1) the sub-domain between the "http://" and the "domain.com"
2) the last part of the URL as it is the product ID to insert into the form information.

Any help with this is most appreciated!

Thanks,

Shawn





Vader
Hi Shawnlevin,
To get the different pieces of the url of the webpage you are on using JavaScript you can use the window.location object along with the JavaScript Split function.

Here is a quick example of window.location in use to get the entire URL.

<script type="text/javascript">

completeURL= window.location;
document.write(completeURL);

</script>

To get the current URL in the parts you requested you can use the following:

<script type="text/javascript">

//sample url = vader.samplesite.com/light/saber/

fullDomain = window.location.host;
//this will give you javascript.samplesite.com

domainArray = fullDomain.split('.');
//this splits your domain in pieces using the "."

subDomain=domainArray[0];
document.write(subDomain);
//this will give you the subdomain portion ie vader

domain=domainArray[1];
document.write(domain);
//get and print the domain name only ie samplesite

domainExt=domainArray[2];
document.write(domainExt);
//get and print the domain extension ie com

urlPath=window.location.pathname;
document.write(urlPath);
//get and print the portion of your url after the domain extension ie /light/saber/

</script>

If you would like to get a specific portion of your urlPath then this can be achieved using the JavaScript Split method once more but with a minor adjustment.

<script type="text/javascript">

// this will give you your path ie /light/saber/
urlPath=window.location.pathname;

//this splits your url in pieces using the / as a separator
urlPathArray = urlPath.split('/');

//get the first section of your path ie light
urlPath1=urlPathArray[1];
document.write(urlPath1);

</script>

Vader
Friday, 6th November 2009
Votes:
27
11

More JavaScript Help:
» How can I automatically submit a form using JavaScript?
» How to create an online voting or survey system using JavaScript?
» Catching up events outside an iframe
» Send mail to user when he had submitted data in database
» Using Javascript to Create a new row
» Preloader gif or adsense that appears before the game loads
» JavaScript get element by class?
» Word Count in JavaScript, how to count the number of words?