支持正则表达式的 String 对象的方法的其中replace()
方法的用法
把aabb
换成bbaa
var reg = /(\w)\1(\w)\2/g;
var str = "aabb";
console.log(str.replace(reg,"$2$2$1$1"));//"bbaa"
console.log(str.replace(reg,function($,$1,$2){
return $2+$2+$1+$1;
}))
把the-first-name
变成theFirstName
var reg = /-(\w)/g;
var str = "the-first-name";
var result = str.replace(reg,function($,$1){
return $1.toUpPerCase();
})
console.log(result)//"theFirstName"
正向预查,正向断言
var str = "aabaaaa";
var reg = /a(?=b)/g;
str.match(reg);//a
正则简单的去重
var str = "aaaabbbbbccccc";
var reg = /(\w)\1*/g;
console.log(str.replace(reg,"$1"));//abc
把"1000000000"变成"100.000.000"这种写法,把后面往前面查,三位加个点
var str = "100000000";
var reg = /(?=(\B)(\d{3})+$)/g;
console.log(str.replace(reg,"."))//"100.000.000"
网友评论