I have a language selector dropdown in my site.
On change of the language the URL redirects to the respective site
My Current URL is
https://www.example.com/mem/ca/en/pages/home.aspx
On change of the language, the URL should be like
https://www.example.com/mem/ca/en/pages/home.aspx - on selecting english
https://www.example.com/mem/ca/el/pages/home.aspx - on selecting Español
https://www.example.com/mem/ca/py/pages/home.aspx - on selecting Pусский and so on for all the languages
<pre>
$("#dd-language").on("change", function() {
var countryAppend = $(this).val();
var pathArray = window.location.pathname.split('/')[4];
var res = pathArray.replace(pathArray,countryAppend);
var newURL = window.location.host + "/" + pathArray;
window.location = newURL;
});
</pre>
This adds the value at the end of the URL but I need it to replace the language code in the URL
Once you have the array of the pathname split by /, overwrite the [2]nd item in the array with the new language, then join by /s again:
$("#dd-language").on("change", function() {
var countryAppend = $(this).val();
var pathArray = window.location.pathname.split('/');
pathArray[2] = countryAppend;
var newURL = window.location.host + pathArray.join('/');
window.location = newURL;
});
Eg, for
/mem/ca/en/pages/home.aspx
On splitting by /, the 2nd item in the array will be the ca:
const pathArr = '/mem/ca/en/pages/home.aspx'.split('/');
pathArr[2] = 'el';
console.log(pathArr.join('/'));
so reassigning that array item and then joining results in the desired output.
document.querySelector('#dd-language').addEventListener('change',function(){
let url = window.location.href.split('/');
url[5] = this.value;
url = url.join('/');
window.location = url;
});
A regular expression should be useful here
$("#dd-language").on("change", function() {
var countryAppend = $(this).val();
var url = location.href;
window.location = url.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages");
});
Example
countryAppend ="xx"
console.log(
`https://www.example.com/mem/ca/en/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages"),
`https://www.example.com/mem/us/el/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages"),
`https://www.example.com/mem/mx/py/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages")
)
Related
Sorry for asking simple questions.
I have url with like this :
http://sub.maindomain/page/title
I want to add
/en/
in the middle of my url so it will be change to
http://sub.maindomain/en/page/title
thank you for your help
var str='http://sub.maindomain/page/title';
var en='en/';
var position= str.indexOf('page')
alert(str.substr(0, position) + en + str.substr(position));
i guess there will be always page in that url so i found it's index,
and added en before it's index
If you want to change the actual URL with a new URL parameter en in the address bar. You can try this.
var newUrl = location.origin + '/en' + location.pathname
document.location.href = newUrl
Supposing you're in a context where document is available (since your post is taggued jQuery, it's most likely the case):
const href = 'http://sub.maindomain/page/title?foo=bar#hash';
// Build a link element
const link = document.createElement('a');
link.href = href;
// Add '/en' before its pathname
const result = link.protocol + '//' + link.host + '/en' + link.pathname + link.search + link.hash;
console.log(result);
in case if page is not on after domain some other string is there then try below code.
var str = 'http://sub.maindomain/page/title';
var arr = str.split(/\//);
arr.splice(3, 0, 'en');
str = arr.join('/');
let url = "http://sub.maindomain/page/title";
let textToAdd = "en/";
//Split the url string into array of two elements and then join them together with a new string 'en/page' as a separator
let newUrl = url.split('page').join(`${textToAdd}page`);
console.log(newUrl);
I have this URL
http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb
I want to replace the last part of my URL which is c939c38adcf1873299837894214a35eb with something else.
How can I do it?
Try this:
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
somethingelse = 'newhash';
var newUrl = url.substr(0, url.lastIndexOf('/') + 1) + somethingelse;
Note, using the built-in substr and lastIndexOf is far quicker and uses less memory than splitting out the component parts to an Array or using a regular expression.
You can follow this steps:
split the URL with /
replace the last item of array
join the result array using /
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
var res = url.split('/');
res[res.length-1] = 'someValue';
res = res.join('/');
console.log(res);
Using replace we can try:
var url = "http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb";
var replacement = 'blah';
url = url.replace(/(http.*\/).*/, "$1" + replacement);
console.log(url);
We capture everything up to and including the final path separator, then replace with that captured fragment and the new replacement.
Complete guide:
// url
var urlAsString = window.location.href;
// split into route parts
var urlAsPathArray = urlAsString.split("/");
// create a new value
var newValue = "routeValue";
// EITHER update the last parameter
urlAsPathArray[urlAsPathArray.length - 1] = newValue;
// OR replace the last parameter
urlAsPathArray.pop();
urlAsPathArray.push(newValue);
// join the array with the slashes
var newUrl = urlAsPathArray.join("/");
// log
console.log(newUrl);
// output
// http://192.168.22.124:3000/temp/box/routeValue
You could use a regular expression like this:
let newUrl = /^.*\//.exec(origUrl)[0] + 'new_ending';
I want to parse some urls's which have the following format :-
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
Its not necessary that the domain name and other parts would be same for all url's, they can vary i.e I am looking at a general solution.
Basically I want to strip off all the other things and get only the part:
/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p
I thought to parse this using JavaScript and Regular Expression
I am doing like this:
var mapObj = {"/^(http:\/\/)?.*?\//":"","(&mycracker.+)":"","(&ref.+)":""};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
url = url.replace(re, function(matched){
return mapObj[matched];
});
But its returning this
http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43pundefined
Where am I not doing the correct thing? Or is there another approach with an even easier solution?
You can use :
/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/
Code :
var s="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var ss=/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/;
console.log(s.match(ss)[1]);
Demo
Fiddle Demo
Explanation :
Why don't you just map a split array?
You don't quite need to regex the URL, but you will have to run an if statement inside the loop to remove specific GET params from them. In this particular case (key word particular) you just have to substring till the indexOf "&mycracker"
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var x = url.split("/");
var y = [];
x.map(function(data,index) { if (index >= 3) y.push(data); });
var path = "/"+y.join("/");
path = path.substring(0,path.indexOf("&mycracker"));
Change the following code a little bit and you can retrieve any parameter:
var url = "http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var re = new RegExp(/http:\/\/[^?]+/);
var part1 = url.match(re);
var remain = url.replace(re, '');
//alert('Part1: ' + part1);
var rf = remain.split('&');
// alert('Part2: ' + rf);
var part2 = '';
for (var i = 0; i < rf.length; i++)
if (rf[i].match(/(p%5B%5D|sid)=/))
part2 += rf[i] + '&';
part2 = part2.replace(/&$/, '');
//alert(part2)
url = part1 + part2;
alert(url);
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var newAddr = url.substr(22,url.length);
// newAddr == "/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
22 is where to start slicing up the string.
url.length is how much of it to include.
This works as long as the domain name remains the same on the links.
For example:
example.com/fun/browse/apples/bananas
example.com/browse/gerbals/cooties
How can I find the keyword "browse", regardless of where it is in the url, and remove the following url part. In the above cases that would be "apples" and "gerbals"
I tried spliting it by the "/" and getting the indexOf browse, then removing the next item, but I cant seem to join everything together because that creates a double "//" in the new url.
Any help would be appreciated.
Javascript and jQuery both ok.
NOTE: I do not want to remove any other part of the url. I want to keep everything. I want to only remove the part of the url immediately after browse.
Your question is unclear but let's try :
var s = 'example.com/fun/browse/apples/bananas';
s.replace(/(\/browse)\/[^\/]+/, '$1'); // "example.com/fun/browse/bananas"
Also check this helper :
function removeAfter(s, keyword) {
return s.replace(
new RegExp('(\/' + keyword + ')\/[^\/]+'), '$1'
);
}
Usage :
var s = 'example.com/browse/gerbals/cooties';
removeAfter(s, 'browse'); // "example.com/browse/cooties"
removeAfter(s, 'gerbals'); // "example.com/browse/gerbals"
Demo : http://jsfiddle.net/wared/VRJtL/.
remove browser by using .splice() & rejoin it.
var arr = "example.com/fun/browse/apples/bananas".split('/');
var index = arr.indexOf("browse");
arr.splice(index+1,1); //removes apples
var URL = arr.join('/'); //joins back
result: "example.com/fun/browse/bananas"
Split the URL on the Keyword...
example:
var url = "http://www.foo.com/bar/alpha/beta";
var keyword = "alpha";
var result = url.split(keyword)[0];
//result = "http://www.foo.com/bar/" + keyword;
//adding the keyword is if you need the keyword in your response.
If you're not trying to remove 'fun' part, it's really simple:
var url = 'example.com/fun/browse/apples/bananas';
var result = url.replace(/browse\/[a-zA-Z\/]+/, 'browse/gerbals/cooties');
I'll throw out another option, just to make it interesting. :)
var url = "http://example.com/fun/browse/apples/bananas";
var targetWord = "browse";
var regexPattern = new RegExp("(^.*" + targetWord + "/?)[^/]*/?(.*$)");
var newURL = "";
var matchedURLparts = regexPattern.exec(url);
if (matchedURLparts) {
newURL = (matchedURLparts.length > 2) ? matchedURLparts[1] + matchedURLparts[2] : matchedURLparts[1];
}
else {
newURL = url;
}
I have got a current URL looking like this:
http://example?variables1=xxxx&example&variables2=yyyyy
I want to use the variables1 and variables2 to create a new URL and open this new URL:
http://example?variables3=variables1&example&variables4=variables2
I hope someone can help me with this :)
You will need to parse the desired query parameters from the first URL and use string addition to create the second URL.
You can fetch a specific query parameter from the URL using this code. If you were using that, you could get variables1 and variables2 like this:
var variables1 = getParameterByName("variables1");
var variables2 = getParameterByName("variables2");
You could then use those to construct your new URL.
newURL = "http://example.com/?variables1=" +
encodeURIComponent(variables1) +
"&someOtherStuff=foo&variables2=" +
encodeURIComponent(variables2);
Because I don't fully understand what needs to change, here's my best attempt*, using a mashup of other answers and resources online.
// the original url
// will most likely be window.location.href
var original = "http://example?variables1=xxxx&example&variables2=yyyyy";
// the function to pull vals from the URL
var getParameterByName = function(name, uri) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(uri);
if(results == null) return "";
else return decodeURIComponent(results[1].replace(/\+/g, " "));
};
// so, to get the vals from the URL
var variables1 = getParameterByName('variables1', original); // xxxxx
var variables2 = getParameterByName('variables2', original); // yyyyy
// then to construct the new URL
var newURL = "http://" + window.location.host;
newURL += "?" + "variables3=" + variables1;
newURL += "&example&"; // I don't know what this is ...
newURL += "variables4=" + variables2;
// the value should be something along the lines of
// http://example?variables3=xxxx&example&variables4=yyyy
*All of which is untested.