正则表达式一些高级用法demo
var str = "aaaa"
var reg = /(a)\1/g // 这里的“\1表示反向引用前面匹配的结果”
var str = "aaaa"
var reg = /(\w)\1/g
str.match(reg) // ["aa", "aa"]
(2) ["aa", "aa"]
var str2 = "aa"
var reg = /a/g
console.log(str2.replace(reg, "b")) // bb
VM1469:3 bb
var str2 = "aabb"
var reg2 = /(\w)\1(\w)\2/g;
str2.match(reg2)
["aabb"]
var str2 = "aa"
console.log(str2.replace("a", "b"))
VM1427:2 ba
var str2 = "aabb"
var reg = /(\w)\1(\w)\2/g
console.log(str2.replace(reg, "$2$2$1$1")) // bbaa
VM1512:3 bbaa
var str2 = "aabb"
var reg = /(\w)\1(\w)\2/g
console.log(str2.replace(reg, function($, $1, $2){
return $2 + $2 + $1 +$1 // 这里也可以随意扩展
}))
VM1622:3 bbaa
// the-first-name
// thisFirstName
var reg = /-(\w)/g;
var str = "the-first-name";
console.log(str.replace(reg, function($, $1) {
console.log($1, '$1')
return $1.toUpperCase();
}))
VM2237:6 f $1
VM2237:6 n $1
VM2237:5 theFirstName
var str = "aaaba"
var reg = /a(?=b)/g // 正向预查找后面是b的a
var reg1 = /a(?!b)/g //查找后面不是b的a
console.log(str.match(reg))
VM2451:3 ["a"]
var str = "aaaba"
var reg = /a+/g // 能多不少
console.log(str.match(reg))
VM2486:3 (2) ["aaa", "a"]
var str = "aaaba"
var reg = /a+?/g //能少不多
console.log(str.match(reg))
VM2492:3 (4) ["a", "a", "a", "a"]
// aaaaaaaaabbbbbbbbbccccc
// abc
var str = "aaaaaaaaaaabbbbbbbbbcccccc"
var reg = /(\w)\1*/g
console.log(str.replace(reg,"$1"))
VM2718:5 abc
// 1000000000000
//100.000.000.000
var str = "100000000000"
var reg = /(?=(\B)(\d{3})+$)/g
console.log(str.replace(reg,"."))
VM3104:5 100.000.000.000
var str = "my name is ${name} ,age is ${age}"
var info = {
name: 'AAA',
age: 33
}
function printf(str, info){
Object.keys(info).forEach((key)=>{
str = str.replace(new RegExp('\\${'+key+'}'), info[key])
})
console.log(str)
}
printf(str, info)
VM3659:12 my name is AAA ,age is 33