壹题git
第 105 题:编程题url有三种状况github
https://www.xx.cn/api?keyword=&level1=&local_batch_id=&elective=&local_province_id=33 https://www.xx.cn/api?keyword=&level1=&local_batch_id=&elective=800&local_province_id=33 https://www.xx.cn/api?keyword=&level1=&local_batch_id=&elective=800,700&local_province_id=33 复制代码
匹配elective后的数字输出(写出你认为的最优解法):正则表达式
[] || ['800'] || ['800','700'] 复制代码
常看法法有两种:编程
// 后行断言:(?<=y)x
function getElective1(url) {
if (!url) {
return;
}
const params = url.match(/(?<=elective=)(\d+(,\d+)*)/);
return params ? params[0].split(',') : [];
}
// 前行断言:x(?=y)
function getElective2(url) {
if (!url) {
return;
}
return (/elective=(?=(\d+(,\d+)*))/).test(url) ? RegExp.$1.split(',') : [];
}
复制代码
function getElective3(url) {
if (!url) {
return;
}
const params = new URLSearchParams(url).get('elective');
return params ? params.split(',') : [];
}
复制代码
兼容性来自 MDN:api