views:

466

answers:

4

Given a series of URLs

http://www.anydotcom.com/myfolder/some-url.html
http://www.anydotcom.com/myfolder2/index.html#
http://www.anydotcom.com/myfolder3/index.html?someParam=aValue
http://www.anydotcom.com/foldername/index.html?someParam=anotherValue
First, how could I strip anything off the end of the URL so that I end up with
http://www.anydotcom.com/myfolder/some-url.html
http://www.anydotcom.com/myfolder2/index.html
http://www.anydotcom.com/myfolder3/index.html
http://www.anydotcom.com/foldername/index.html
or, ideally, I would like it to return
/myfolder/some-url.html
/myfolder2/index.html
/myfolder3/index.html
/foldername/index.html
I've tried
    var thisUrl = "" + window.location;
    var myRegExp = new RegExp("([^(\?#)]*)");
    thisUrl = myRegExp.exec(thisUrl);

but this returns

http://www.anydotcom.com/foldername/index.html,http://www.anydotcom.com/foldername/index.html

and I don't quite understand why.

I appreciate any help here!

+1  A: 

If you are using window.location, you can simply access the wanted data by using:

var thisUrl = window.location.pathname;

If you are extracting stuff from links, the following regular expression will get you what you need:

// Supports all protocols (file, ftp, http, https, whatever)
var pathExtract = /^[a-z]+:\/\/\/?[^\/]+(\/[^?]*)/i;
var thisUrl = (pathExtract.exec(someUrl))[1];
Andrew Moore
Ugh. That's what I get for not completely checking out the location object. Thank you for the quick answer.
And thanks to the other, also correct, answers.
A: 

Javascript location object

var loc = window.location;
var thisUrl = loc.protocol + "//" + loc.hostname + loc.pathname;
Josh Stodola
Another great answer. Thanks!
+1  A: 

Well, to answer your question directly, here's the regular expression to do that.

thisUrl = thisUrl.replace( /^https?:\/\/[^\/]|\?.*$/g, '' );

However, since you mention window.location in your code, you can actually get this data straight from the location object.

thisUrl = top.location.pathname;
Peter Bailey
Thank you for answering my original question first before showing me the error of my ways! I definitely need to start researching existing properties of an object before trying to reinvent the wheel.
A: 

using the object window.location is simple as write:

function getPath() {
    return window.location.pathname;
}
dfa