Skip to content

Instantly share code, notes, and snippets.

@damiancipolat
Last active May 4, 2019 17:41
Show Gist options
  • Save damiancipolat/f44865ef8eb2142eeaf34bed41e7244f to your computer and use it in GitHub Desktop.
Save damiancipolat/f44865ef8eb2142eeaf34bed41e7244f to your computer and use it in GitHub Desktop.
URL Parser Exercise in JS
//Parse and extract data from a string like: param1=111&param2=222&param3=333
const parseQryStr = (url)=>{
//Match xxx=yyy
const paramRegex = '[a-zA-Z0-9]=[a-zA-Z0-9]';
//Split the params.
const params = url.split('&');
//Extract the variables if match with the format.
let values = {};
params.forEach(param=>{
if (param.match(paramRegex)){
const parts = param.split('=');
values[parts[0]] = parts[1];
}
});
return values;
}
//Parse and extract data from a string like: /:version/api/:collecton/:id
const parseBySlash = (format,url)=>{
//Variable format :xxxxx.
const varRegex = '^:[a-zA-Z0-9]';
//Split by format and url.
const fmtChunks = format.split('/');
const urlChunks = url.split('/');
//If the format not match.
if (!(urlChunks.length >= fmtChunks.length))
throw new Error('Url format error');
//Extract the values and match with format.
let values = {};
fmtChunks.forEach((fmt,i)=>{
if (fmt.match(varRegex)){
const atrib = fmt.replace(':','');
values[atrib] = urlChunks[i];
}
});
return values;
}
//Receive the url and format and parse it.
const parse = (format,url)=>{
const parts = url.split('?');
//If the url have two sections, merge it.
return (parts.length > 1)
? {...parseBySlash(format,parts[0]),...parseQryStr(parts[1])}
: parseBySlash(format,url);
}
//TESTING
let format = '/:version/api/:collecton/:id';
let url1 = '/6/api/listings/3?sort=desc&limit=10';
let url2 = '/6/api/listings/3';
let url3 = 'sort=desc&limit=10';
let tmp = parse(format,url3);
console.log(tmp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment