How to parse a URL?

If there is one thing I just cant get my head around, it's regex.

So after a lot of searching I finally found this one that suits my needs:

function get_domain_name()
        domain_name_parts = aaaa.match(/:\/\/(.[^/]+)/)[1].split('.');
        if(domain_name_parts.length >= 3){
            domain_name_parts[0] = '';
        var domain = domain_name_parts.join('.');
        if(domain.indexOf('.') == 0)
            alert("1"+ domain.substr(1));
            alert("2"+ domain);

It basically gives me back the domain name, is there anyway I can also get all the stuff after the domain name? in this case it would be /blah/sdgsdgsdgs from the aaaa variable.



Please note that this solution is not the best. I made this just to match the requirements of the OP. I personally would suggest looking into the other answers.

THe following regexp will give you back the domain and the rest. :\/\/(.[^\/]+)(.*):

  2. /goosomething

I suggest you studying the RegExp documentation here:

Using your function:

function get_domain_name()
        var matches = aaaa.match(/:\/\/(?:www\.)?(.[^/]+)(.*)/);

Instead of relying on a potentially unreliable* regex, you should instead use the built-in URL parser that the JavaScript DOM API provides:

var url = document.createElement('a');
url.href = "";

That's all you need to do to parse the URL. Everything else is just accessing the parsed values:

url.protocol; //(http:)
url.hostname; //(
url.pathname; //(/some/path); // (?name=value)
url.hash; //(#anchor)

In this case, if you're looking for /blah/sdgsdgsdgs, you'd access it with url.pathname

Basically, you're just creating a link (technically, anchor element) in JavaScript, and then you can make calls to the parsed pieces directly. (Since you're not adding it to the DOM, it doesn't add any invisible links anywhere.) It's accessed in the same way that values on the location object are.

(Inspired by this wonderful answer.)

EDIT: An important note: it appears that Internet Explorer has a bug where it omits the leading slash on the pathname attribute on objects like this. You could normalize it by doing something like:

 url.pathname = url.pathname.replace(/(^\/?)/,"/");

Note: *: I say "potentially unreliable", since it can be tempting to try to build or find an all-encompassing URL parser, but there are many, many conditions, edge cases and forgiving parsing techniques that might not be considered or properly supported; browsers are probably best at implementing (since parsing URLs is critical to their proper operation) this logic, so we should keep it simple and leave it to them.


You just need to modify your regex a bit. For example:

var aaaa="";
var m = aaaa.match(/^[^:]*:\/\/([^\/]+)(\/.*)$/);

m will then contain the following parts:

["", "", "/blah/sdgsdgsdgs"]

Here is the same example, but modified so that it will split out the "www." part. I think the regular expression should be written so that the match will work whether or not you you have the "www." part. So check this out:

var aaaa="";
var m = aaaa.match(/^[^:]*:\/\/(www\.)?([^\/]+)(\/.*)$/);

m will then contain the following parts:

["", "www.", "", "/blah/sdgsdgsdgs"]

Now check out the same regular expression but with a url that does not start with "www.":

var bbbb="";
var m = .match(/^[^:]*:\/\/(www\.)?([^\/]+)(\/.*)$/);

Now your match looks like this:

["", undefined, "", "/blah/sdgsdgsdgs"]

So as you can see it will do the right thing in both cases.


There is a nice jQuery plugin for parsing URLs: Purl.

All the regex stuff is hidden inside, and you get something like:

> url = $.url("");

> url.attr('source');

> url.attr('protocol');

> url.attr('host');

> url.attr('relative');

> url.attr('path');

> url.attr('directory');

> url.attr('file');

> url.attr('query');

> url.attr('fragment');

Browsers have come a long way since this question was first asked. You can now use the native URL interface to accomplish this:

const url = new URL('')

console.log( // ""
console.log(url.href) // ""
console.log(url.origin) // ""
console.log(url.pathname) // "/blah/sdgsdgsdgs"
console.log(url.protocol) // "http:"
// etc.

Be aware that IE does not support this API. But, you can easily polyfill it with

<script crossorigin="anonymous" src=""></script>

The RFC (see appendix B) provides a regular expression to parse the URI parts:

 12            3  4          5       6  7        8 9


scheme    = $2
authority = $4
path      = $5
query     = $7
fragment  = $9


function parse_url(url) {
    var pattern = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
    var matches =  url.match(pattern);
    return {
        scheme: matches[2],
        authority: matches[4],
        path: matches[5],
        query: matches[7],
        fragment: matches[9]


    authority: ""
    fragment: undefined
    path: "/blah/sdgsdgsdgs"
    query: undefined
    scheme: "http"



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.