Search code examples
javascriptjqueryurlhreflocation-href

Insert string to url and redirect


Is it possible to insert a stringi into url? Lets say I want www.domain.com/news to insert language flag de between com and news


Solution

  • If you have a full url string that includes protocol or you know the base url or if this is all based on current location you can use the URL API

    const url = new URL('http://www.example.com/news');
    url.pathname = '/de' + url.pathname;
    console.log(url.href);
    
    // using current page `location`
    const pageurl = new URL(location.href);
    pageurl.pathname = '/foobar' + pageurl.pathname;
    console.log(pageurl.href);