将有重复的字符提取出来,例如 12323454545666,提取 [‘23’, ‘45’, ‘6’]
const collectReplaceStr = (str) => {
let replaceStrs = [];
const replaceRe = /(.+)\1+/g;
str.replace(replaceRe, ($0, $1) => {
$1 && replaceStrs.push($1);
});
}
2.实现一个 trim 函数
//去除空格法
const trim = (str) => {
return str.replace(/^\s*|\s*$/g, '');
}
//提取非空格法
const trim = (str) => {
return str.replace(/^\s*(.*?)\s*$/g, '$1');
}
将 123456789 变成 123,456,789
第一步:尝试先把后面第一个逗号弄出来
'123456789'.replace(/(?=\d{3}$)/, ',');
第二步:把所有的逗号都弄出来
'123456789'.replace(/(?=(\d{3})+$)/g, ',');
第三步:去掉首位的逗号
'123456789'.replace(/(?!^)(?=(\d{3}+$))/g, ',');
将手机号 18379836654 转化为 183-7983-6654
'18379836654'.replace(/(?=(\d{4})+$)/g, '-');
如下规则,将对应字符串变成驼峰写法
1. foo Bar => fooBar
2. foo-bar--- => fooBar
3. foo_bar__ => fooBar
//1. 每个单词的前面都有 0 个或者多个 - 空格 _
//2.- 空格 _ 后面有可能不跟任何东西
const camelCase = (str) =>{
const camelCaseRegex = /[-_\s]+(.)?/g;
return str.replace(camelCaseRegex, ($0, $1)=>{
return $1 ? $1.toUpperCase() : '';
});
}
console.log(camelCase('foo bar'));
console.log(camelCase('foo-bar--'));
console.log(camelCase('foo_bar__'));
例如 hello world 转为 Hello Word
const capitalize = (str) => {
const capitalizeRegex = /(?:^|\s+)\w/g;
return str.toLowerCase().replace(capitalizeRegex, ($0)=>{
return $0.toUpperCase();
});
}
const getQueryByName = (name) => {
const queryRegex = new RegExp(`[?&]${name}=([^&]*)(?:&|$)`);
const queryNameMatch = window.location.search.match(queryRegex);
return queryNameMatch ? decodeURICompenent(queryNameMatch[1]) : '';
}
//1. name 在最前面 http://baidu.com?name=test&age=30
//2. name 在最后 http://baidu.com?age=30&name=test
//3. name 在中间 http://baidu.com?age=30&name=test&hobby=soccer
getQueryByName('name');