I have a langauge dropdown, and a javascript function which changes the page to the corresponding language selected. I need help on my regex replace:
For example, I would like this URL to turn into this url: http://localhost:7007/en/Product/Detail/1038 http://localhost:7007/fr/Product/Detail/1038
function languageChange(sender) {
var lang = $(sender).val();
var target = window.location.href;
target = target.replace(/(http:\/\/.*?)([a-zA-Z]{2})(.*$)/gim, '1ドル' + lang + '3ドル');
window.location = target;
}
3 Answers 3
Is your URL always the same structure? If so, you may not need a regex at all. Split the url at each "/", replace index 3, then join your array back to together with "/".
Here is a code sample:
function changeLanguage(url, newLang) {
var url = url.split('/');
url[3] = newLang;
return url.join('/');
}
changeLanguage('http://localhost:7007/en/Product/Detail/1038','Fr');
Note: I originally wrote "splice" instead of "join" in my response. Join is the correct method.
Comments
Here is a function that processes any number of URLs within a string, and replaces the language part (the first part of path), only if exists and is from 2 to 4 chars long:
function changeLanguage(text, lang) {
return text.replace(
/\b(\w+:\/\/[^\/]+\/)[A-Z]{2,4}(?=[\/\s]|$)/gim,
'1ドル' + lang);
}
Edit: Converted to function format.
Comments
Use this regex:
target =
target.replace(/(https?:\/\/[^/]+)\/?([^/]*)(.*)/gi, '1ドル/' + lang + '3ドル');
if e.g. lang='fr'
then target
holds http://localhost:7007/fr/Product/Detail/1038
value;
1 Comment
/(https?:\/\/[^/]+\/?)([^/]+)(.*)/gim
doesn't work if the URL path is empty. (The regex does not require a /
) Given the URL: http://localhost:7007
this returns http://localhost:700fr
.