繁体   English   中英

如何使用正则表达式替换其他两个字符串并删除最后5个字符

[英]How to replace string between two others and remove last 5 characters using regex

我正在尝试创建一个书签,使我可以操纵一些URL,以便在新的CMS中的内容编辑视图和生产之间快速切换。

目前,我可以用CMS版本替换URL的乞求字符串,这很棒。 但是,我还需要能够删除字符串末尾的“ .html”,这是我正在努力解决的问题。

我现在有什么

以下是我当前的书签:

<a href="javascript:(function(){window.location=window.location.toString
().replace(/^http(.*)\/en\//,'https://cms.ca/en_lg/').replace(/^https:(.*)
\/fr\//,'https://cms.ca/fr_lg/');})();">Switch - CMS</a>

使用上面的书签,我可以执行以下操作(由于它们不是真正的链接,因此删除了前面的“ h”):

更改此:

  • ttp://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html

对此:

  • ttps://cms.ca/en_lg/folder/anotherfolder/anotherfolder/page.html

我想做的事

更改此:

  • ttp://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html“

对此:

  • ttps://cms.ca/en_lg/folder/anotherfolder/anotherfolder/page

请注意,字符串末尾的.html已被删除。

这可以用一种替换方法吗? 如果是这样,我是否还可以将检查/ en_lg /或/ fr_lg /的事实合并为一个表达式?

任何帮助将非常感激!

如果可以的话,只需忽略/ en_lg /和/ fr_lg /:

.replace(/^http:\\/\\/www.webby.yay.com\\/(.*)\\.html$/,'https://cms.ca/$1')

例如:

"http://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html".replace(/^http:\\/\\/www.webby.yay.com\\/(.*)\\.html$/,'https://cms.ca/$1')

"https://cms.ca/en_lg/folder/anotherfolder/anotherfolder/page"

是的,您可以使用捕获组将这两个或三个替换方法合并为一个:

window.location.toString().replace(/^http:\/\/.*?\/(en|fr)(.*?)(\.\w+)?$/, 'https://cms.ca/$1_lg$2')

演示:

 var url = "http://www.webby.yay.com/en/folder/anotherfolder/anotherfolder/page.html" console.log(url.replace(/^http:\\/\\/.*?\\/(en|fr)(.*?)(\\.\\w+)?$/, 'https://cms.ca/$1_lg$2')) 

暂无
暂无

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

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