Parse Url Structure By Regular Expression
I have one URL pattern : product/[cat]/[page].[ext] product/category/page.html product/page.html But my Regular Expression does not work properly : ^product\/([\w\d\.\-_\s\'\'\(\)\
Solution 1:
Is this regular expression solving your problem ?
^product\/([a-zA-Z]+)\/*([a-zA-Z]+)\.([a-zA-Z]+)
Try some cases on my Regex101
Solution 2:
this is function to generate regression solved your problem.
functionmakeRegEx(route, url) {
let pattern = newRegExp('(:([a-z]+))(\\??)', 'g');
let match = route.match(pattern);
let route_regex = route.replace(/\//g, '\\/').replace(/\./g, '(\\.*)');
for(let params of match) {
let required = params.includes('?') ? '*' : '+';
route_regex = route_regex.replace(params, '([a-z_\\-]'+required+')')
}
let params_match = url.match(route_regex);
let map_params;
if (params_match) {
map_params = match.map((item, key) => { return {param: item, value: params_match[key + 1]} });
} else {
map_params = 'missing required params';
}
return {
url, route, route_regex, map_params
}
}
// test cases:console.log(makeRegEx('product/:cat/:page.html', 'product//.html'));
console.log(makeRegEx('product/:cat/:page.html', 'product/computer/.html'));
console.log(makeRegEx('product/:cat/:page.html', 'product/computer/cpu.html'));
console.log(makeRegEx('product/:cat/:page?.html', 'product//cpu.html'));
console.log(makeRegEx('product/:cat/:page?.html', 'product/computer/.html'));
console.log(makeRegEx('product/:cat/:page?.html', 'product/computer/cpu.html'));
console.log(makeRegEx('product/:cat/:page.:type', 'product/computer/.html'));
console.log(makeRegEx('product/:cat/:page.:type', 'product//.html'));
console.log(makeRegEx('product/:cat/:page.:type', 'product/computer/cpu.html'));
console.log(makeRegEx('product/:cat/:page.:type?', 'product/computer/cpu'));
console.log(makeRegEx('product/:cat/:page.:type?', 'product/computer/cpu.html'));
Post a Comment for "Parse Url Structure By Regular Expression"