12

匹配elective后的数字输出

 5 years ago
source link: https://www.tuicool.com/articles/22QFvmJ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

一、问题

Url 有以下三种情况:

var url_1 = 'https://www.xx.cn/api?keyword=&level1=&local_batch_id=&elective=&local_province_id=33';

var url_2 = 'https://www.xx.cn/api?keyword=&level1=&local_batch_id=&elective=800&local_province_id=33';

var url_3 = 'https://www.xx.cn/api?keyword=&level1=&local_batch_id=&elective=800,700&local_province_id=33';

匹配 elective 后的数字输出(写出你认为的最优解法):

[] || ['800'] || ['800','700']

二、答案

答题可以考虑下以下几点:

- 效率高;

- 可以扩展换 Url ,换字段;

- elective 是跟在一堆空值后面,要效率较高的排除掉前面的匹配;

- 匹配完 elective 的值之后, & 后面的匹配需要立刻停止,减少性能消耗;

- 第三个的 Url 中带了 , ,也要考虑其他符号的可能性。

2.1 方案一
function getUrlValue(url){

if(!url) return;

// let res = url.match(/(?<=elective=)(\d+(,\d+)*)/);

// let res = /(?<=elective=)(\d+(.\d)*)/g.exec(url);

let res = url.match(/(?<=elective=)(\d+(,\d+)*)/);

return res ? res[0].split(',') : [];

}

其中:这个正则表达式 &lt;= 是零宽度断言的写法,断言 elective=有无内容,是匹配elective=的字符的, (?&lt;=elective=) 是指匹配以 elective= 开头的字符串;

(\d+(.\d)*) 指匹配数字开头,可能不定数量逗号分隔后是数字的字符串。

2.2 方案二
function getQueryFromUrl(key, url) {

const matches = url.match(new RegExp(`(\\?|&)${key}=([^&]*)(&|$)`));

return !matches || matches.length <= 0 ? [] : (matches[2] ? matches[2].split(',') : []);

}

getQueryFromUrl('elective' , url_1)
2.3 方案三

IE 不支持。

function getParamsUrl(url) {

var res = new URLSearchParams(url).get('elective');

return res ? res.split(',') : []; 

}

<br/>

<br/>

文章来自: Daily-Interview-Question:第10题 编程题

正则资料可参考: 陈水水的个人博客 正则表达式


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK