Search code examples
javascriptarraysstringbrowserlocation-href

Why window.location.href.split("?") array is changing its value itself


I am trying to reload the page on click of radio buttons (list of cities) by providing the value of radio buttons as query-parameters in URL. Suppose my current URL is

http://localhost:3001/offers?category=Dining&sub_categories=Home%20Delivery&city=

And on the selection of any radio button, I want its value to be added to city parameter in URL. So desired URL should be

http://localhost:3001/offers?category=Dining&sub_categories=Home%20Delivery&city=Mumbai

But the problem is while modifying the URL, the sub_categories are automatically getting stripped off and final URL I am getting is this.

http://localhost:3001/offers?category=Dining&city=Mumbai

Here is my code for manipulating URL:

$(document).on('click', '.city-selector' ,function(event) {
    event.preventDefault() ;
    var city_name = this.labels[0].textContent.trim().split("(")[0].trim() ;
    var location_string = window.location['href'].split('?');
    if(location_string.length > 1 && location_string[1].indexOf("city") > -1){
      var all_params = location_string[1].split("&") ;
      all_params.splice(all_params.indexOf("city=" + gon.selected_city), 1) ;
      all_params.splice(all_params.indexOf("localities=" + gon.selected_localities), 1) ;
      gon.selected_localities = '' ;
      location_string[1] = all_params.join("&") ;
      location_string[1] = location_string[1] + "&city=" + city_name ;
      window.location.href = location_string[0] + "?" +location_string[1] ;
    }

  }) ;

HINT: Problem lies in line location_string = window.location['href'].split('?'); When I log the location_string array it doesn't contain the sub_categories parameter.
Nou sure which thing is stripping it off.


Solution

  • I think you should use regular expression to replace url:

    var url = 'http://localhost:3001/offers?category=Dining&sub_categories=Home%20Delivery&city=';
    
    var cityName = 'Mumbai';
    var cityParams = 'city=' + cityName;
    
    
    var newUrl = url + '&' + cityParams;
    if (url.indexOf('?') === -1) {
        newUrl = url + '?' + cityParams;
    } else if (url.indexOf('city=') > -1) {
        newUrl = url.replace(/(city=[\w\d%_]*)/g, cityParams);
    }
    

    It also working with url like: http://localhost:3001/offers?category=Dining?city=hanoi&sub_categories=Home%20Delivery

    http://localhost:3001/offers