Skip to content Skip to sidebar Skip to footer

Javascript Simple Regex To Find Root Domain

I have a function that uses regex to return root domain of the given url. http://jsfiddle.net/hSpsT/ function cleanUp(url) { url = url.replace(new RegExp(/^\s+/),''); // START

Solution 1:

Extract hostname name from string

Try:

functioncleanUp(url) {
    var url = $.trim(url);
    if(url.search(/^https?\:\/\//) != -1)
        url = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i, "");
    else
        url = url.match(/^([^\/?#]+)(?:[\/?#]|$)/i, "");
    return url[1];
}

alert(cleanUp('  http://www.google.com/about.html'));
alert(cleanUp('  www.google.com/about.html'));

Solution 2:

Try this:

http://jsfiddle.net/picklespy/gb34u/1/

It works on all modern browsers and even on IE 5.5+.

var url = document.createElement('a');
url.href = 'http://maps.test.google.com';
var host = url.hostname;

host = host.split('.');

var domain = host.pop();
domain = host.pop() + '.' + domain;

alert('Root is: ' + domain)

Post a Comment for "Javascript Simple Regex To Find Root Domain"