简体   繁体   中英

Replace a part of the current URL

I want to add a modified link on a 404 page because I moved the permalink structure from domain.tld/category/title to domain.tld/title. Now when a visitor found an old link to domain.tld/category/title she/he will see the 404 page and there should be a dynamic link to domain.tld/title. This link should be generated if window.location.href contains five "/" (because of http://www.domain.tld/category/title/ has five "/" and my new permalink structure won't have five "/" but only four "/". I know I can replace (remove) the category part with this code:

function geturl(){
 var url = window.location.href;
 alert(url.replace('/category/', '/'));
}

The problem with that is that I have to define a static category name but it could be anything. How to get rid of /category/ part dynamically when there are five "/" in window.location.href?

Here you go:

function geturl(url){
    if (typeof url === 'string'){
        var a = document.createElement('a');
        a.href = url;
        url = a.pathname;
    }
    else url = window.location.pathname;
    alert(url.replace(/^\/[^\/]+\//, '/'));
}

Call this function using geturl('your url') . If no url is passed, it'll use the page's current url. The regular expression will replace a string at the beginning of the URL's path portion which is inside 2 / characters.

Preface: this really should be handled by the web server (not your web page), as Mike mentioned.


RegExPal seems to agree with this:

var url = "http://www.domain.tld/category/title/";

url.replace(/\/[^/.]+?\//, "");

Note: not including a "g" in the RegExp will only allow the first instance to be replaced.


That being said, you don't need RegEx. You could just split and then join the URL:

var parts = x.split("/");
parts.splice(3,1);
window.location.href = parts.join("/");

it will remove category from url

 function geturl(){
     var url = window.location.pathname; // get url from browser
    // var url = 'http://www.domain.tld/category/title/'; // get url from browser
     var url_array = url.split('/category/');
     var newurl = url_array[0]+"/"+url_array[1];
     alert(newurl);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM