簡體   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