js regexp group & RegExp.`$1`~`$9` All In One
js regexp group & RegExp.$1
~ RegExp.$9
All In One
信息加密,电话号码隐藏
const phoneNumber = `18123456789`;
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$2');
// '181****2345' ❌
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3');
// '181****6789' ✅
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1$2****');
// '1812345****' ❌
regexp 可视化
https://regexper.com/#%2F^(\d{3})(\d{4})(\d{4})%24%2F
RegExp group
const phoneNumber = `18123456789`;
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, function(match, group1, group2, group3) {
console.log("match, group1, group2, group3 =", match, group1, group2, group3);
});
// match, group1, group2, group3 = 18123456789 181 2345 6789
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, (match, group1, group2, group3) => {
console.log("match, group1, group2, group3 =", match, group1, group2, group3);
});
// match, group1, group2, group3 = 18123456789 181 2345 6789
phoneNumber.replace(/^(\d{3})(\d{4})(\d{4})$/, (match, ...groups) => {
console.log("match, groups =", match, groups);
});
// match, groups = 18123456789 (5) ['181', '2345', '6789', 0, '18123456789']
RegExp.$1
~RegExp.$9
const reg = /(\w+)\s(\w+)/;
const name = 'Eric Xia';
name.replace(reg, '$2 $1');
// "Xia Eric"
RegExp.$1;
// "Eric"
RegExp.$2;
// "Xia"
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/n
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16169157.html
未经授权禁止转载,违者必究!