javascript - 替代正面看背后
问题描述
我刚刚发现正面的外观在旧版浏览器中不起作用,我在 IE11 上遇到了这个问题,即Unexpected quantifier
正则表达式:
/(?<=\d{4})\d(?=\d{4})/g
输入:
const string = 4444333322221111;
string.replace(/(?<=\d{4})\d(?=\d{4})/g, "#");
预期结果:
4444########1111
此正则表达式的任何替代方法都会有所帮助。
解决方案
如果你的字符串只包含数字,你真的不需要正则表达式,你只需要几个字符串操作方法:
// Adapted from https://stackoverflow.com/a/5450113/3832970, count will always be positive here
function strRepeat(pattern, count) {
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
var string = "4444333322221111";
console.log(
string.substring(0,4) + strRepeat("#", string.length-8) + string.slice(-4)
)
如果您需要在较长的字符串中屏蔽用四位数字括起来的数字,您可以使用:
function strRepeat(pattern, count) {
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
var string = "111109876543210000 abc 1234012345678904321";
console.log(
string.replace(/\d{9,}/g, function(match) {
return match.substr(0,4) + strRepeat("#", match.length-8) + match.slice(-4);
})
)
这里,
/\d{9,}/g
匹配所有出现的九个或更多数字function(match) {...}
- 采用正则表达式匹配的回调方法,您可以在此处操作输出match.substr(0,4) + "#".repeat(match.length-8) + match.slice(-4)
- 连接前4位数字,然后附加需要替换的数字,然后#
添加剩余的4位数字。
如果需要,您可以使用捕获组制作正则表达式模式,它会使回调方法更小,但会使正则表达式更长:
function strRepeat(pattern, count) {
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
var string = "111109876543210000 abc 1234012345678904321";
console.log(
string.replace(/(\d{4})(\d+)(\d{4})/g, function($0, $1, $2, $3) {
return $1 + strRepeat("#", $2.length-8) + $3;
})
)
在这里,该(\d{4})(\d+)(\d{4})
模式会将 4 位数字捕获到第 1 组 ( $1
),然后将 1+ 数字捕获到第 2 组 ( $2
),然后将 4 位数字捕获到第 3 组 ( $3
)。
推荐阅读
- jenkins - 如何在jenkinsfile中将内部版本号从一个作业传递到另一个作业以进行构建作业?
- mysql - 错误 1264 (22003):第 1 行的“金额”列的值超出范围
- python - 使用字典过滤 Pandas DataFrame
- c++ - CSActiveMQ CPP 生产者 - 一个会话可以使用多个队列吗?
- selenium - selenium-side-runner 找不到 chromedriver
- vue.js - 安装 @vue/cli 后找不到命令
- python - 使用列表中的值更新 dict 值
- javascript - ReactJS:映射图像数组,每个图像具有唯一的弹出窗口
- php - laravel:如何在路线中使用多“可以”?
- c# - 使用 GraphServiceClient 将字符串段附加到 MS Graph 请求