前端开发工具篇

js如何获取url后面的参数

2019-07-15  本文已影响2人  追逐繁星的阿忠

url如下:用最简便的方式获取对应的参数:

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']

解答一:

new URLSearchParams('https://www.xx.cn/api?keyword=&level1=&local_batch_id=&elective=800,700&local_province_id=33').get('elective')

解答二:

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

解答三:

const urls = [
  "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",
];

function getElective(url) {
  const reg = new RegExp("(^|&)elective=([^&]*)(&|$)", "i");
  const r = url.substr(1).match(reg);

  if (r != null) {
    return r[2] ? r[2].split(",") : [];
  }

  return [];
}

urls.forEach((url) => {
  const result = getElective(url);
  console.log(result, "---result");
});

解答四:


解答五:


原文地址: (https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/177)[https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/177]

曾在网上看到过这样一句话,印象很深:

我之所以选择努力读书,选择努力赚钱,是为了将来远离想娶免费保姆的男人。

不管什么时候,不管在什么地方,读书,应该是一辈子要做的投资。

上一篇 下一篇

猜你喜欢

热点阅读