Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 105 题:编程题(获取url的query) #37

Open
DreamLee1997 opened this issue Oct 7, 2019 · 0 comments
Open

第 105 题:编程题(获取url的query) #37

DreamLee1997 opened this issue Oct 7, 2019 · 0 comments

Comments

@DreamLee1997
Copy link
Owner

url有三种情况
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']

解答:
法一:

function getUrlValue(url){
    if(!url) return;
    let res = url.match(/(?<=elective=)(\d+(,\d+)*)/);
    return res ?res[0].split(',') : [];
}

  • 其中:这个正则表达式 <=是零宽度断言的写法,断言 elective=有无内容,是匹配elective=的字符的,(?<=elective=) 是指匹配以elective=开头的字符串;
  • (\d+(.\d)*)指匹配数字开头,可能不定数量逗号分隔后是数字的字符串。

法二:(IE 不支持)

function getParamsUrl(url) {
  var res = new URLSearchParams(url).get('elective');
  return res ? res.split(',') : []; 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant