user151822
user151822

Reputation:

How to strip all parameters and the domain name from a URL using javascript?

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!

Upvotes: 1

Views: 3613

Answers (4)

Andrew Moore
Andrew Moore

Reputation: 95444

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

Upvotes: 1

dfa
dfa

Reputation: 116442

using the object window.location is simple as write:

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

Upvotes: 0

Peter Bailey
Peter Bailey

Reputation: 105914

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;

Upvotes: 2

Josh Stodola
Josh Stodola

Reputation: 82523

Javascript location object

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

Upvotes: 0

Related Questions