【问题标题】:Replace middle of string given a range替换给定范围的字符串中间
【发布时间】:2023-03-21 08:09:01
【问题描述】:

上一个问题:

如何替换字符串中的间隔字符:

例如Apple to A***e

更新:

需要获取字符位置 0-4 和 -4(反向)

var transaction = '1234567890987651907';
console.log('1234****1907');

解决方案

var str = "01340946380001281972";
str.replace(/^(\d{0,4})(\d{4})(.*)/gi,"$1 **** $2");

【问题讨论】:

  • 到目前为止你尝试过什么?什么是区间字符?
  • 0-4 到 -4 字符 示例:1234567890 到 1234**7890
  • 请更新您的问题,而不是发布带有示例的 cmets。你的例子根本不清楚。您想给出一个范围并将该范围更改为 *?
  • 我的英语不太好,抱歉……但我确实更新了。
  • 所以苹果到苹果是区间1,-1,第二个是区间4到-4?

标签: javascript regex replace


【解决方案1】:

我想你是这个意思

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

使用切片

const maskIt = (str,keep) => {
  return str.slice(0,keep)+Array.from({length: str.length-keep-1},() => '*').join('')+ str.slice(-keep)
}
console.log(
  maskIt("1234567890",4),
  maskIt("Apple",1)
)

【讨论】:

    【解决方案2】:

    这是使用基本字符串函数的解决方案:

    var input = "Apple";
    var input_masked = input.substring(0, 1) + Array(input.length - 1).join("*") +
        input.substring(input.length-1);
    console.log(input_masked);

    这种方法是将中间字符(掩码为*)夹在输入的第一个字符和最后一个字符之间。

    【讨论】:

    • 你可以简化更多吗?
    • 大声笑...我不知道,我可以简化更多吗?
    • 我试试: var str = "Mandarina"; str.replace(/^(\w{0,4})(\w{0,4})/g,"$1 **** $2");
    • 你是在浪费大家的时间吗?
    • 我的英语不太好,抱歉……但我确实更新了。
    【解决方案3】:

    只替换中间的字符:

    const str = "Apple";
    const output = `${str[0]}${"*".repeat(str.length - 2)}${[...str].pop()}`;
    console.log(output);

    【讨论】:

    • 他想告诉函数在开始时保留多少,在结束时保留多少,可能是对称的
    【解决方案4】:
    var str = "01340946380001281972";
    str.replace(/^(\d{0,4})(\d{4})(.*)/gi,"$1 **** $2");
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2012-08-21
      • 1970-01-01
      • 2012-12-05
      • 2012-09-16
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      相关资源
      最近更新 更多