Home > Back-end >  Replace pathname and origin using Javascript
Replace pathname and origin using Javascript

Time:05-11

I have a function where I get some data via a rest-call and put it into a div with an id schnittstelle-01.

const request = new XMLHttpRequest();
request.open(
    'GET',
    'https://purl.ulb.tu-darmstadt.de/vp/r000000-2001?ed=pa000008',
);
request.addEventListener('load', function (event) {
    if ((request.status = 200)) {
        document.getElementById('schnittstelle-01').innerHTML =
            request.responseText;
        console.log(request.responseText);
        for (let el of document.querySelectorAll('#schnittstelle-01 * a'))
            el.href = el.href.replace(
                window.location.origin,
                'purl.ulb.tu-darmstadt.de/vp/',
                
            );
    } else {
        console.log(request.status);
    }
});
request.send();

The retrieving part is not what bothers me, but the el.href.replace() part... Let's say my url is test.de the link are supposed to lead to purl.ulb.tu-darmstadt.de/vp/{link-target} at the moment the links after this point to purl.ulb.tu-darmstadt.de/vp/path-to-site-on-test.de/{link-target}

I cannot figure out how to replace both parts. Any hints would be appreciated! I think I'm missing sth. basic here ...

all the best,

CodePudding user response:

you need location.pathname

el.href = el.href.replace(
    location.origin   location.pathname,
    'purl.ulb.tu-darmstadt.de/vp/',
 );
  • Related