0

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;
}
asked Apr 6, 2011 at 15:33

3 Answers 3

2

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.

answered Apr 6, 2011 at 15:45

Comments

2

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.

answered Apr 6, 2011 at 15:58

Comments

1

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;

answered Apr 6, 2011 at 15:45

1 Comment

This regex: /(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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.