字符串能使用正则的方法match(),search(),split(),replace()

163 阅读1分钟

string字符串能使用正则的方法

match()

匹配失败时返回null

let string = 'zhangjinxi'
string.match(String|Reg);

当reg没有g修饰符时,只匹配第一个匹配项,返回[match,index,input],match匹配项,index匹配项的索引,input原字符串,index和input不计入数组长度,如下:

alt text转存失败,建议直接上传图片文件

有g修饰符时,只有match,没有input和index,如下:

alt text转存失败,建议直接上传图片文件

search()

忽视g修饰符,返回结果和string.indexOf()方法一样

let string = 'zhangjinxi'
string.search(string|reg);

split()

字符串分割成数组,size为保留的数组的长度

let string = 'zhangjinxi'
string.split(string|reg,size);

replace()

Reg不添加g,默认匹配第一个。

// 函数的用法,前面的参数时匹配到的分组,后面两个分别是匹配项在字符串的位置和原字符串,返回要替换成的字符串。
string.replace(string|reg,string|function(match1,match2...,position,originString));

如下图:

下面是两个小技巧

  • 日期格式化

n代表匹配到的第n个分组n代表匹配到的第n个分组 &最近一次匹配项,匹配项之前的文本,`匹配项之前的文本,'匹配项之后的文本

  • 找出连续重复最多的字符和个数
let maxLength = 0;
let maxValue = '';
'aabbbcccc'.replace(/(\w)\1+/g,function(match,pos,origin){
    if(match.length>maxLength){
        maxLength = match.length;
        maxValue = match; 
    }
})
console.log(maxLength,maxValue); // 4 'c'

如下图: