美文网首页
JS正则之其他捕获方法(replace)

JS正则之其他捕获方法(replace)

作者: 金刚狼_3e31 | 来源:发表于2020-11-24 09:44 被阅读0次
replace字符串中实现替换的方法(一般都是伴随正则一起使用的)
let str = 'nihao@2019|nihao@2020';
1. 不用正则,执行一次只能替换一个
str = str.replace('nihao', '你好').replace('nihao', '你好');
2. 使用正则会简单一点
str = str.replace(/nihao/g, '你好');

案例:把时间字符串进行处理
let time = '2019-08-13';
// 变为'2019年08月13日'
let reg = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
// 这样可以实现
// time = time.replace(reg, '$1年$2月$3日');
// console.log(time);   //=>2019年08月13日

// 还可以这样处理 [str].replace([reg], [function])
// 1. 首先拿到reg和time进行匹配捕获,能匹配到几次就会把传递的函数执行几次(而且是匹配一次就执行一次)
// 2. 不仅把方法执行,而且replace还给方法传递了实参信息(和exec捕获的内容一致的信息:大正则匹配的内容,小分组匹配的信息)
time = time.replace(reg, (big, $1, $2, $3) => {
    // 这里的$1~$3是我们自己设置的变量
    console.log(big, $1, $2, $3);
});
time = time.replace(reg, (...arg) => {
    let [, $1, $2, $3] = arg;
    $2.length < 2 ? $2 = '0' + $2 : null;
    $3.length < 2 ? $3 = '0' + $3 : null;

    return $1 + '年' + $2 + '月' + $3 + '日';
});

案例:单词首字母大写
let str = 'good good study, day day up!';
let reg = /\b([a-zA-Z])[a-zA-Z]*\b/g;
// 函数被执行了六次,每一次都把正则匹配信息传递给函数
// 每一次arg: ['good', 'g'] ['good', 'g'] ['study', 's']...
str = str.replace(reg, (...arg) => {
    let [content, $1] = arg;
    $1 = $1.toUpperCase();
    content = content.substring(1);
    
    return $1 + content;
});

案例:JS正则之最多出现字母的补充方法
let str = 'jsljsljpsjkfdhiofhjjqdkjslj';
     max = 0,
     res = [],
     flag = false;
str = str.split('').sort((a, b) => a.localCompare(b)).join('');
for (let i = str.length; i > 0; i--) {
    let reg = new RegExp('([a-zA-Z])\\1{' + (i - 1) + '}', 'g');
    str.replace(reg, (content, $1) => {
        res.push($1);
        max = i;
        flag = true;
    })
    if (flag) break;
}
console.log(`出现次数最多的字符:${res}, 出现了${max}次`);

案例:JS正则表达式之时间字符串格式化
/*
* formatTime: 时间字符串的格式化处理
*     @params
*         template: [string]  我们最后期望获取日期格式的模板
*         模板规则:{0}->年  {1~5}->月日时分秒
 *    @return 
 *          [string]格式化后的时间字符串
 */
function formatTime(template = '{0}年{1}月{2}日 {3}时{4}分{5}秒') {
    //首先获取时间字符串中的年月日等信息
    let timeAry = this.match(/\d+/g);
    return template.replace(/\{(\d+)\}/g, (content, $1) => {
        //content: 当前本次大正则匹配的信息  $1: 本次小分组单独匹配的信息
        //以$1的值作为索引,到timeAry中找到对应的时间(如果没有则用‘00’补)
        let time = timeAry[$1] || '00';
        if (time.length < 2) time = '0' + time;
        return time;
    });
}

案例:JS正则表达式之queryURLParams
function queryURLParams() {
    let obj = {};
    this.replace(/([^?=&#]+)=([^?=&#]+)/g, (...[, $1, $2]) => obj[$1] = $2);
    this.replace(/([^?=&#]+)/g, (...[, $1]) => obj['HASH'] = $1);
    return obj;
}

案例:JS正则表达式之千分符
funtion millimeter() {
    return this.replace(/\d{1, 3}(?=(\d{3})+$)/g, content => content + ',');
}

//把以上方法扩展到内之类String.prototype上
['formatTime', 'queryURLParams', 'millimeter'].forEach(item => {
    String.prototype[item] = eval(item);
});

相关文章

网友评论

      本文标题:JS正则之其他捕获方法(replace)

      本文链接:https://www.haomeiwen.com/subject/jbwviktx.html