如何使用正则表达式替换其他两个字符串并删除最后 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/')
例如:
"http://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html".replace(/^http:\/\/www.webby.yay.com\/(.*)\.html$/,'https://cms.ca/')
给予
"https://cms.ca/en_lg/folder/anotherfolder/anotherfolder/page"
是的,您可以使用捕获组将这两个或三个替换方法合并为一个:
window.location.toString().replace(/^http:\/\/.*?\/(en|fr)(.*?)(\.\w+)?$/, 'https://cms.ca/_lg')
演示:
var url = "http://www.webby.yay.com/en/folder/anotherfolder/anotherfolder/page.html"
console.log(url.replace(/^http:\/\/.*?\/(en|fr)(.*?)(\.\w+)?$/, 'https://cms.ca/_lg'))
我正在尝试创建一个小书签,它允许我操作一些 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/')
例如:
"http://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html".replace(/^http:\/\/www.webby.yay.com\/(.*)\.html$/,'https://cms.ca/')
给予
"https://cms.ca/en_lg/folder/anotherfolder/anotherfolder/page"
是的,您可以使用捕获组将这两个或三个替换方法合并为一个:
window.location.toString().replace(/^http:\/\/.*?\/(en|fr)(.*?)(\.\w+)?$/, 'https://cms.ca/_lg')
演示:
var url = "http://www.webby.yay.com/en/folder/anotherfolder/anotherfolder/page.html"
console.log(url.replace(/^http:\/\/.*?\/(en|fr)(.*?)(\.\w+)?$/, 'https://cms.ca/_lg'))