Antonio Ortiz Antonio Ortiz - 5 months ago 12
Javascript Question

How can I strip out a the base URL using JavaScript?

I have this function from a previous problem, and it works great however I just realized my collection of links need to have the base URL stripped out.

These are the parts which I thought would strip out the baseURL:

baseUrlPattern = /^https?:\/\/[a-z\:0-9.]+/; // create the regexp

link.href.replace(baseUrlPattern ,""); // then use replace to strip it out of the URL


UPDATE

I should have mentioned:

The function already can discover the link and apply the attribute, but doesn't strip out the base URL.

This:

<a href="http://url.nyc.com/xxx/xxx/xxx">link1</a>


Should look like this in the DOM afterwards:

<a href="/xxx/xxx/xxx" target="_blank">link1</a>


JS:

var URLChecker = (function iffe() {
var publicAPI = {
getURL: function() {
for (var i = 0; i < arguments.length; i++) {
return {
'smo': 'http://url.nyc.com',
'smodev': 'http://smodev.rye.foo.com',
'url1_sans_3w': 'http://url1.com',
'url2': 'http://www.url2.com',
'url3': 'http://www2.url3.com'
}[arguments[i]];
}
},
searchURL: function() {
var link, url, baseUrlPattern = /^https?:\/\/[a-z\:0-9.]+/;
for (var i = 0, len = arguments.length; i < len; i++) {
url = this.getURL(arguments[i]);
for (var j = 0, jlen = document.links.length; j < jlen; j++) {
link = document.links[j];
if (link.href.indexOf(url) !== -1) {
link.setAttribute("target", "_blank");
link.href.replace(baseUrlPattern ,"");

}
}
}
}
};
return publicAPI;
})();


HTML:

<a href="http://url.nyc.com/xxx/xxx/xxx">link1</a>
<br>
<a href="http://smodev.rye.foo.com/xxx/xxx/xxx">link2</a>
<br>
<a href="http://url1.com/xxx/xxx/xxx">link3</a>
<br>
<a href="http://www.url2.com/xxx/xxx/xxx">link4</a>
<br>
<a href="http://www.url3.com/xxx/xxx/xxx">link5</a>

Answer

There's different ways you can go about this, here's one of them:

See comments below

searchURL: function() {
    var link, url, parser; //added parser
    for (var i = 0, len = arguments.length; i < len; i++) {
        url = this.getURL(arguments[i]);
        for (var j = 0, jlen = document.links.length; j < jlen; j++) {
                link = document.links[j];
            if (link.href.indexOf(url) !== -1) {
                // create a dummy link just to get the pathname of the actual link
                parser = document.createElement('a');
                parser.href = link.href;

                link.setAttribute("target", "_blank");
                link.href = parser.pathname;
            }
        }
    }
}

Should you need anything else, remember the parser just an anchor so you have the following

var href = "http://url.nyc.com/xxx/xxx/xxx"; 
parser = document.createElement('a'); 
parser.href = href; 

console.dir(parser);

parser.protocol; // => "http:"
parser.hostname; // => "url.nyc.com"
parser.port;     // => ""
parser.pathname; // => "/xxx/xxx/xxx"
parser.search;   // => ""
parser.hash;     // => ""
parser.host;     // => "url.nyc.com"