简体   繁体   English

替换当前网址的一部分

[英]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. 我想在404页上添加修改后的链接,因为我将永久链接结构从domain.tld / category / title移到了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. 现在,当访问者找到到domain.tld / category / title的旧链接时,他/他将看到404页面,并且应该有指向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: 如果window.location.href包含五个“ /”,则应生成此链接(因为http://www.domain.tld/category/title/包含五个“ /”,而我的新的永久链接结构不会包含五个“ /” “,但只有四个” /“。我知道我可以用以下代码替换(删除)类别部分:

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? 在window.location.href中有五个“ /”时,如何动态地删除/ category /部分?

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') . 使用geturl('your url')调用此函数。 If no url is passed, it'll use the page's current url. 如果没有传递任何URL,它将使用页面的当前URL。 The regular expression will replace a string at the beginning of the URL's path portion which is inside 2 / characters. 正则表达式将替换URL路径部分开头的字符串,该字符串位于2 /字符内。

Preface: this really should be handled by the web server (not your web page), as Mike mentioned. 前言:正如Mike所说,这确实应该由Web服务器(而不是您的网页)处理。


RegExPal seems to agree with this: RegExPal似乎对此表示赞同:

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. 注意:在RegExp中不包含“ g”将仅允许替换第一个实例。


That being said, you don't need RegEx. 话虽如此,您不需要RegEx。 You could just split and then join the URL: 您可以split然后join 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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