jquery remove part of url

2019-09-05 10:02发布

问题:

Lets say i've got the following url;

http://www.domain.com/en-US/assortment/en-US/category/page.aspx?sub=GROUP7

As you can see I have two language layers in the url from which I want to remove ONLY the second one. So I expect the url to be like this.

http://www.domain.com/en-US/assortment/category/page.aspx?sub=GROUP7

Due to technical limitations I don't have any other ways to modify the url. Can this be achieved with jQuery or Javascript? If yes, how?

回答1:

'your url here...'.replace( '/assortment/en-US/category/', '/assortment/category/');


回答2:

Check out the JavaScript replace function.

Well, using the replace function, you can do something ugly like this:

var url= "http://www.domain.com/en-US/assortment/en-US/category/page.aspx?sub=GROUP7";

var index = url.lastIndexOf('en-US');  //get last index of language
var substr = url.substr(index);        //get substring of the tail
var newsubstr = substr.replace('en-US','');  //use replace to get rid of second lang
var newurl = url.substr(0,index-1); //first part of the url
var cleanurl = newurl + newsubstr;  //concatenate it
alert(cleanurl);

I didn't really take time to make this cleaner - I'll clean it up in a few minutes.



回答3:

Because you are referring a language code, I'll write a javascript code to catch generic language code and replace the duplication.

You can do this easily with regular expressions. check this out

url = "http://www.domain.com/en-US/assortment/en-US/category/page.aspx?sub=GROUP7"

//define regular expression to catch /en-US block
// '/' in front of the language code is also catch in this regular expression
rxp = /(\/[\w]{2}(-[\w]{2})?)/

//split by regular expression
ary = url.split(rxp)

//set the fourth eliment to "" the 4th eliment is the second '/en-US'
ary[3] = "" 

//join array with "" to have the prepare the string
url_new = ary.join("")

the parameter inside the join method is essential.

This should work on most of the language codes currently in use.