正则的风骚操作

个位数字字符数组去重

1
2
3
4
5
6
7
8
9
function noRepeatReg (arr) {
return arr.sort().join('').replace(/(\d)\1*/g, '$1').split('')
}

const arr = ['0', '2', '3', '2', '3', '1', '1']

const res = noRepeatReg(arr)

console.log(res)

单词尾部追加

1
2
3
4
5
6
7
8
9
10
function addReg (str) {	
let i = 5
return str.replace(/\w+/g, w => w + i++)
}

const str = 'yya yyb yyc'

const res = addReg(str)

console.log(res)

trim

1
2
3
function trim (str) {	
return str.replace(/\^\b|\b\$/g, '')
}