Javascript 如何使用正则表达式替换其他两个字符串之间的字符串并删除最后5个字符
我正在尝试创建一个bookmarklet,它允许我操作一些URL,以便在新CMS中在内容编辑视图和产品之间快速切换 目前,我能够用CMS版本替换URL的乞讨字符串,这很好。但是,我还需要能够删除字符串末尾的“.html”,这正是我正在努力解决的问题 我现在拥有的 以下是我当前的bookmarklet:Javascript 如何使用正则表达式替换其他两个字符串之间的字符串并删除最后5个字符,javascript,regex,bookmarklet,Javascript,Regex,Bookmarklet,我正在尝试创建一个bookmarklet,它允许我操作一些URL,以便在新CMS中在内容编辑视图和产品之间快速切换 目前,我能够用CMS版本替换URL的乞讨字符串,这很好。但是,我还需要能够删除字符串末尾的“.html”,这正是我正在努力解决的问题 我现在拥有的 以下是我当前的bookmarklet: <a href="javascript:(function(){window.location=window.location.toString ().replace(/^http(.*)\
<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>
使用上面的bookmarklet,我可以执行以下操作(我删除了前面的“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
如果可以忽略/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'))
非常感谢您的建议。我本应该更清楚一些,但我尝试替换的字符串可以涵盖各种不同的内容。例如,我可以得到如下URLttp://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html 或ttp://whatisthis.com/fr_lg/folder/example/anotherfolder/test.html 或ttp://www.iamnotasite.hi.coolstuffbro.com/fr\u lg/cool/cool.html。我基本上想替换http之间的所有内容,直到fr\u lg或en\u lg,然后在最后删除html。如何。替换(/^(.*)/(en\u lg fr\u lg)\/(.*)html$/,'https://cms.ca/$2/$3')
?