上一个问题:
如何替换字符串中的间隔字符:
例如从Apple到A *** e
更新:
需要获取char位置0-4和-4(反向)
var transaction = '1234567890987651907';
console.log('1234****1907');
解决方案
var str = "01340946380001281972";
str.replace(/^(\d{0,4})(\d{4})(.*)/gi,"$1 **** $2");
答案 0 :(得分:0)
这是使用基本字符串函数的解决方案:
var input = "Apple";
var input_masked = input.substring(0, 1) + Array(input.length - 1).join("*") +
input.substring(input.length-1);
console.log(input_masked);
这种方法是在输入的第一个字符和最后一个字符之间夹住中间字符(掩码为*
)。
答案 1 :(得分:0)
只需替换中间字符:
const str = "Apple";
const output = `${str[0]}${"*".repeat(str.length - 2)}${[...str].pop()}`;
console.log(output);
答案 2 :(得分:0)
var str = "01340946380001281972";
str.replace(/^(\d{0,4})(\d{4})(.*)/gi,"$1 **** $2");
答案 3 :(得分:0)
我想你是这个意思
function maskIt(str, keep) {
var len = str.length,
re = new RegExp("(.{" + keep + "})(.{" + (len - keep * 2) + "})(.{" + keep + "})", "g")
console.log(re)
return str.replace(re, function(match, a, b, c) {
return a + ("" + b).replace(/./g, "*") + c
});
}
console.log(
maskIt("1234567890", 4),
maskIt("Apple", 1)
)
作为原型:
String.prototype.maskIt = function(keep) { // don't use arrow or lose "this"
const re = new RegExp("(.{" + keep + "})(.{" + (this.length - keep * 2) + "})(.{" + keep + "})", "g");
return this.replace(re, (match, a, b, c) => a + ("" + b).replace(/./g, "*") + c);
}
console.log(
"1234567890".maskIt(4),
"Apple".maskIt(1)
)