简体   繁体   中英

Need a Javascript regex expression to match a language param in URL

I'm not familiar with regex and I haven't found any proper solution for my case. My website utilizes such URLs:

(http(s)://www.)website.com/en/someURL
(http(s)://www.)website.com/anotherURL
(http(s)://www.)website.com/de/anotherURL

If website.com/someURL , website.com/ or website.com is accessed the default language will be loaded.

I need a regex which will allow only these certain language codes, case sensitivity is not important:

(http(s)://www.)website.com/en
(http(s)://www.)website.com/en/
(http(s)://www.)website.com/
(http(s)://www.)website.com
(http(s)://www.)website.com/de
(http(s)://www.)website.com/de/

This regex will work:

^((https?)?\:\/\/www\.)?website\.com(\/((de|en)\/?)?)?$

If you want to make some unit tests on [ https://regex101.com/][1] you should erase the ^ and $ for beginning and end, otherwise you will see a positive result only if you use only one line.

For testing you could use this (if you want you can add some lines):

https://www.website.com/en
http://www.website.com/en/
https://www.website.com/
https://www.website.com
https://www.website.com/de
https://www.website.com/de/

you only have to limit the number of letters to two and with that you get the language \\w{2}

https?\:\/\/www\.website\.com\/((\w{2})\/?$|(\w{2})\/)

eg https://regex101.com/r/SCbDyY/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