Alaa M. Tekleh Alaa M. Tekleh - 3 months ago 11
jQuery Question

Ajax request with slash separated parameters

I have to deal with API that follow slash separated parameters in URL like this

http://example.com/api/get_nearest_places/:en_type_id/:longtude/:latitude


I know that I can build a URL as string pieces like the following

var longtude = 33.42432;
var latitude = 42.3243;
var en_type_id = 1;
var url = "http://example.com/api/get_nearest_places/"+en_type_id+"/"+longtude+"/"+latitude;


Then pass this URL Ajax function, but this is ugly way to manage especially if there are a lot of request so this way isn't practical

I'm wondering if that is a JavaScript function or library that take a JOSN object that have parameters of a URL and URL it self and do parameters matching then return URL, or in more beauty way take a base URL as parameter, function name, and parameters in JSON object

Answer

Little late to the game, but I would use Object.keys with for each if you want to loop over the object that holds the values.

function urlReplace(url, params) {
  Object.keys(params).forEach(function(key) {
    //url = url.replace(new RegExp(":" + key), params[key]);
    url = url.replace(":" + key, params[key]);
  });
  return url;
}


var url = urlReplace("http://example.com/api/get_nearest_places/:en_type_id/:longtude/:latitude", {
  longtude: 33.42432,
  latitude: 42.3243,
  en_type_id: 1
});

console.log(url);

Or you can go from a regular expression to the object. This is nice if you have an object that might have more keys that what would be in the url. No wasted time looping over the invalid keys.

function urlReplace(url, params) {
  return url.replace(/:([^\/]+)/g, function(match, key) {
    return params[key];
  });
}


var url = urlReplace("http://example.com/api/get_nearest_places/:en_type_id/:longtude/:latitude", {
  longtude: 33.42432,
  latitude: 42.3243,
  en_type_id: 1
});

console.log(url);