replace字符串替换
var str = "abcxyza"
var newstr = str.replace("a","*")
//newstr的值为*bcxyz
$1,$2的使用
const reg= /(\d{3})\d*(\d{4})/
let phoneNum = "18311118902"
const res = phoneNum.replace(reg, '$1****$2')
console.log(res) // "183****8902"
$1对应正则表达式中第一个小括号内表达式所对应的内容(\d{3})
$2则为第二个
如:这是一个实现类型判断的函数
function getType(target) {
// 先进行 typeof 判断,如果是基础数据类型,直接返回。
const type = typeof target;
if (type !== "object") {
return type;
}
// 如果是引用类型或者 null,再进行如下的判断,正则返回结果,注意最后返回的类型字符串要全小写。
return Object.prototype.toString
.call(target) //[object Xxx]
.replace(/^\[object (\S+)\]$/, "$1")
.toLocaleLowerCase();
}
其他字符替换
字符 | 替换文本 |
$& | 与 regexp 相匹配的子串。 |
$` | 位于匹配子串左侧的文本。 |
$' | 位于匹配子串右侧的文本。 |
$$ | 直接量符号。 |