首页 > 解决方案 > 替代正面看背后

问题描述

我刚刚发现正面的外观在旧版浏览器中不起作用,我在 IE11 上遇到了这个问题,即Unexpected quantifier

正则表达式: /(?<=\d{4})\d(?=\d{4})/g

输入: const string = 4444333322221111;

string.replace(/(?<=\d{4})\d(?=\d{4})/g, "#");

预期结果: 4444########1111

此正则表达式的任何替代方法都会有所帮助。

标签: javascriptregex

解决方案


如果你的字符串只包含数字,你真的不需要正则表达式,你只需要几个字符串操作方法:

// 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)。


推荐阅读