一。字符串的includes方法:
应用:
//将网址加上后面的键值 // https://www.imooc.com/course/list // https://www.imooc.com/course/list?c=fe&sort=pop let url = 'https://www.imooc.com/course/list'; const set_url_param = (url, name, value) => { // url += url.includes('?') ? '&' : '?'; // url += `${name}=${value}`; url = url + (url.includes('?') ? '&' : '?'); url = url + `${name}=${value}`; return url; } url = set_url_param(url, 'c', 'fe'); url = set_url_param(url, 'sort', 'pop'); console.log(url);//https://www.imooc.com/course/list?c=fe&sort=pop
代码优化:
(1)先使用includes方法判断是url中否包含?
(2)如果包含?, 再判断url最后一位字符是不是?或&符号,是的话就拼接空字符串,不是的话就拼接&符号
(3)如果不包含?, 就拼接一个?
(4)可以通过url.substr(url.length-1,1)获取字符串最后一个字符
标签:ES6,www,url,新增,includes,course,https,方法,imooc From: https://www.cnblogs.com/zhoushangquan/p/17057572.html