1

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!

4 Answers 4

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

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.
That regex is removing the first character.
1

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];

1 Comment

Ugh. That's what I get for not completely checking out the location object. Thank you for the quick answer.
0

Javascript location object

var loc = window.location;
var thisUrl = loc.protocol + "//" + loc.hostname + loc.pathname;

Comments

0

using the object window.location is simple as write:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.