壹題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