在此示例中,如何使用正则表达式更改URL的语言部分?

How to change language part of URL by using regex in this example?

提问人:Rickyforcode 提问时间:8/16/2023 更新时间:8/16/2023 访问量:61

问:

情况:

选择 id 元素后,获取当前 URl 并将 /en/ 部分更改为其他语言

当前 URL

http://127.0.0.1:5500/2023/en/activities_summary.html

我想把它改成

http://127.0.0.1:5500/2023/tc/activities_summary.html

法典:

    $('#tc').on('click',function(){
           
              
            if(location.href.match(/\/(?:en|sc)\//)){
                location.replace(/^.+?\/(?:en|sc)\//,'tc') 
            }
        })
jQuery 正则表达式

评论

2赞 Wiktor Stribiżew 8/16/2023
也许,没有?location.href = location.href.replace(/\/(?:en|sc)\//, '/tc/')if

答:

1赞 Alexander Nenashev 8/16/2023 #1

(?<=\/\d{4}\/)- 您的年份部分(4 位数字) - 您的语言部分(2 个字符)

- 右斜杠部分
[a-z]{2}(?=\/)

const url = 'http://127.0.0.1:5500/2023/en/activities_summary.html';

console.log(url.replace(/(?<=\/\d{4}\/)[a-z]{2}(?=\/)/, 'tc'));