解析 URL Params 为对象
let url = 'http://www.domain.com/?user=anonymous&id=123&id=456&city=%E5%8C%97%E4%BA%AC&enabled';
parseParam(url)
let url = 'http://www.domain.com/?user=anonymous&id=123&id=456&city=%E5%8C%97%E4%BA%AC&enabled'
let targetObj = parseParam(url);
console.log(targetObj)
function parseParam (url) {
const paramsStr = /.+\?(.+)$/.exec(url)[1];
const paramsArr = paramsStr.split('&');
let paramsObj = {};
paramsArr.forEach(param => {
if (/=/.test(param)) {
let [key, val] = param.split('=');
val = decodeURIComponent(val);
val = /^\d+$/.test(val) ? parseFloat(val) : val;
if (paramsObj.hasOwnProperty(key)) {
paramsObj[key] = [].concat(paramsObj[key], val);
} else {
paramsObj[key] = val;
}
} else {
paramsObj[param] = true;
}
})
return paramsObj;
}
模板引擎实现
let template = '我是{{name}},年龄{{age}},性别{{sex}}'
let data = {
name: '姓名',
age: 18
}
let result = render(template, data);
console.log(result);
function render (template, data) {
const reg = /\{\{(\w+)\}\}/;
if (reg.test(template)) {
const name = reg.exec(template)[1];
template = template.replace(reg, data[name]);
return render(template, data);
} else {
return template;
}
}
查找字符串中出现最多的字符和个数
let str = "abcabcabcbbccccc";
let num = 0;
let char = '';
str = str.split('').sort().join('');
let re = /(\w)\1+/g;
str.replace(re, ($0, $1) => {
if (num < $0.length) {
num = $0.length;
char = $1;
}
})
console.log('字符串中出现次数最多的字符是'+char+',出现次数为'+num)
字符串查找
a='34';b='1234567';
let targetIndex = isContain(a, b);
console.log(targetIndex)
function isContain (a,b) {
for (let i in b) {
if (a[0] === b[i]) {
let tmp = true;
for (let j in a) {
if (a[j] !== b[~~i + ~~j]) {
tmp = false;
}
}
if (tmp) {
return i
}
}
}
return -1
}