2017-07-24 86 views
0

我试图创建一个书签,它允许我操纵一些URL以便在新的CMS中快速切换内容编辑视图和生产。如何使用正则表达式替换另两个字符串之间的字符串并删除最后5个字符

目前,我可以用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

这样:

  • 载荷大小://cms.ca/en_lg/folder /anotherfolder/anotherfolder/page.html

什么,我想要做的

更改此:

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

这样:

  • 载荷大小://cms.ca/en_lg /文件夹/ anotherfolder/anotherfolder /页

注意,的.html在字符串的结尾已被删除。

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

任何帮助将不胜感激!

回答

-1

是的,你可以将这些两个或也许三替代方法合并成一个使用捕获组:

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'))

0

如果没关系简单地忽略/ 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"

+0

非常感谢你的建议。我应该已经更清楚了,但我想要替换的字符串可以包含各种不同的东西。 例如,我可以获取像ttp://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html或ttp://whatisthis.com/fr_lg/folder/example/anotherfolder/的URL test.html或ttp://www.iamnotasite.hi.coolstuffbro.com/fr_lg/cool/cool.html。我基本上想要替换http之间的所有内容,直到fr_lg或en_lg,然后在最后删除html。 – Oaryx

+0

'.replace(/ ^(。*)\ /(en_lg | fr_lg)\ /(。*)\ .html $ /','https://cms.ca/$2/$3')''? – unilynx

相关问题