简体   繁体   中英

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.

Currently, I am able to replace the begging string of the URL with the CMS version, which is great. However, I also need to be able to remove the ".html" at the end of the string, which is what I'm struggling with.

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.):

CHANGE THIS:

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

TO THIS:

  • ttps://cms.ca/en_lg/folder/anotherfolder/anotherfolder/page.html

WHAT I WANT TO DO

CHANGE THIS:

  • ttp://www.webby.yay.com/en_lg/folder/anotherfolder/anotherfolder/page.html"

TO THIS:

  • ttps://cms.ca/en_lg/folder/anotherfolder/anotherfolder/page

Notice that the .html at the end of the string has been removed.

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?

Any help would be much appreciated!

If it's okay to simply ignore /en_lg/ and /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')) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM