Search code examples
jqueryparsingurlsplitstrip

Complete stripping of URL with jquery


This might be pretty straight forward. But i can't figure out a stable solution.

For example:
http://site1.com/promotion

I want to strip my url so i only get the "site1"-part of the URL.

I tried with:

var url = window.location.href.split('http://')[1];
var stripOne = url.split('/')[0];
var stripTwo = stripOne.split('.')[0];

But that comes out inconsistent depending on whether or not the url contains www. or not.

UPDATED WITH CORRECT ANSWER

var url = window.location.href;
url = url.replace(/http:\/\/(www.)?/,'');
var stripOne = url.split('.')[0];

Solution

  • You could use a replace that will strip out 'http://' and 'www.' (if it exists). You could still fall foul of https URLs with this though -

    url = url.replace(/http:\/\/(www.)?/,'');
    var stripTwo = url.split('.')[0];
    

    Demo - http://jsfiddle.net/Ux9jx/