Brandon Brandon - 2 months ago 7
Javascript Question

How can I get everything after the forward slash in my url?

When I visit my url, my script will get the current URL and store it in a variable with

var currentURL = (document.URL);


I'd like to get everything after the forward slash in my url because there will be a hash ID after the forward slash like this:

www.mysite.com/XdAs2


so this is what would be stored in my variable currentURL and I'd like to take only the
XdAs2
from it and store that into another variable. In addition, I'd like to know two other things.


  1. Is document.URL the best way to get the current URL or will I have issues with some browsers?

  2. If I were to try to open that URL using an iframe, will document.URL still work? or must there be an address bar present containing the url? I would really appreciate answers for those questions three questions. Thank you


Ved Ved
Answer

Here's some pseudo code:

var currentURL = (document.URL);
var part = currentURL.split("/")[1];
alert(part); // alerts "XdAs2" !!! 

EDIT

Woops! The pseudo code doesn't work :) though it should give you a general idea of how to get what you need.

1) document.URL should work fine in all major browsers. For more info refer to this Mozilla Developer Network article or this SO question

2) for an iframe, you need to write something like: document.getElementById("iframe_ID").src.toString()

Comments