[英]How to replace string between two others and remove last 5 characters using regex
I'm trying to create a bookmarklet that will allow me to manipulate some URLs in order to quickly switch between content editing views and production in a new CMS. 我正在尝试创建一个书签,使我可以操纵一些URL,以便在新的CMS中的内容编辑视图和生产之间快速切换。
Currently, I am able to replace the begging string of the URL with the CMS version, which is great. 目前,我可以用CMS版本替换URL的乞求字符串,这很棒。 However, I also need to be able to remove the ".html" at the end of the string, which is what I'm struggling with.
但是,我还需要能够删除字符串末尾的“ .html”,这是我正在努力解决的问题。
WHAT I HAVE NOW 我现在有什么
The following is my current bookmarklet: 以下是我当前的书签:
<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>
With the above bookmarklet, I can do the following (I removed the 'h' at the front since they're not real links.): 使用上面的书签,我可以执行以下操作(由于它们不是真正的链接,因此删除了前面的“ h”):
CHANGE THIS: 更改此:
TO THIS: 对此:
WHAT I WANT TO DO 我想做的事
CHANGE THIS: 更改此:
TO THIS: 对此:
Notice that the .html at the end of the string has been removed. 请注意,字符串末尾的.html已被删除。
Is this possible to do with one replace method? 这可以用一种替换方法吗? If so, could I also combine the fact that I check for either /en_lg/ or /fr_lg/ into one expression?
如果是这样,我是否还可以将检查/ en_lg /或/ fr_lg /的事实合并为一个表达式?
Any help would be much appreciated! 任何帮助将非常感激!
If it's okay to simply ignore /en_lg/ and /fr_lg/: 如果可以的话,只需忽略/ en_lg /和/ fr_lg /:
.replace(/^http:\\/\\/www.webby.yay.com\\/(.*)\\.html$/,'https://cms.ca/$1')
eg: 例如:
"http://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html".replace(/^http:\\/\\/www.webby.yay.com\\/(.*)\\.html$/,'https://cms.ca/$1')
gives 给
"https://cms.ca/en_lg/folder/anotherfolder/anotherfolder/page"
Yes, you can merge those two or maybe three replace methods into one using capturing groups: 是的,您可以使用捕获组将这两个或三个替换方法合并为一个:
window.location.toString().replace(/^http:\/\/.*?\/(en|fr)(.*?)(\.\w+)?$/, 'https://cms.ca/$1_lg$2')
Demo: 演示:
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.