使用正则表达式在JavaScript中屏蔽日期的后两位

时间:2018-08-10 16:33:29

标签: javascript regex

我正试图演示在显示日期时如果将某些字符屏蔽后的样子。具体来说,是这样的:

  • 2018年8月10日=> 8月10日**
  • 2018年8月10日=> 8月10日****(如果可能的话也是如此)

我花了一些时间在此处查找工作示例,但没有找到用于此特定示例的示例。在我自己的实验中,我只用一个星号(19年8月10日*)结束,而不是每个字符一个。

这一切都需要在textToMask.replace(regex, '*')内发生。

我知道您永远不会在生产中使用它;这是一个视觉演示。

5 个答案:

答案 0 :(得分:2)

您可以使用padEnd方法

function maskIt(str, pad = 1) {
  const slicedStr = str.slice(0,pad*-1);
  const masked = slicedStr.padEnd(str.length, '*');
  console.log(masked);
}
maskIt("10 August 2018",2);
maskIt("10 August 2018",4);

答案 1 :(得分:1)

这是一个简单的mask()函数,可用于任何字符串,并且不涉及正则表达式:

function mask(str, amt = 1) {
  if (amt > str.length) {
    return '*'.repeat(str.length);
  } else {
    return str.substr(0, str.length-amt) + '*'.repeat(amt);
  }
}

console.log(mask('10 August 2018', 2));
console.log(mask('10 August 2018', 4));
console.log(mask('test', 5));

答案 2 :(得分:0)

这是一个非常简单的函数,它使用正则表达式在给定日期的末尾查找给定数目的数字,并用相等数量的星号代替它们。

示例:

const mask_date = (date, n) => date.replace(new RegExp(`[\\d]{${n}}$`), "*".repeat(n));

console.log(mask_date("10 August 2018", 2));
console.log(mask_date("10 August 2018", 4));

答案 3 :(得分:0)

请注意,我真的很想以某种方式重构它,只是我现在没有时间这样做。明天再回来查看一下,我可能对此做了修改,以使代码流程更好一些。

我正在使用String.prototype.replace函数的第二个版本,该版本允许您传递函数而不是字符串作为第二个参数。检查链接以了解更多信息。

这是一个非常粗糙的功能-不幸的是,我没有很多时间来写出来。

// str - string to be altered, pattern - regex pattern to look through, replacement - what to replace the found pattern with, match_length - do we match the length of replacement to the length of what it is replacing?
function mask(str, pattern, replacement="*", match_length=true){
  
   return str.replace(pattern, function(whole, group){
    
    //init some values;
    let padLength = 0, returned = '';
    
    // if the group is not a number, then we have a regex that has a grouping. I would recommend limiting your regex patterns to ONE group, unless you edit this.
    if(typeof group != 'number'){
      padLength = group.length;
      returned  = whole.slice(0, whole.indexOf(group)) + (replacement.repeat(match_length ? padLength : 1));
    }else{
      padLength = whole.length;
      returned = replacement.repeat(match_length ? padLength : 1);
    }
    return returned;
  });
  
}

let randomBirthdayString = 'April 3 2002';

console.log(mask(randomBirthdayString, /\d{2}(\d{2})$/) );
console.log(mask(randomBirthdayString, /\d{2}(\d{2})$/, 'x') );
console.log(mask(randomBirthdayString, /\d{2}(\d{2})$/, 'x', false) );

答案 4 :(得分:-1)

您可以使用下面的代码。

textToMask.replace(/..$/, '**')