The mask part of the string using RegExp

I am trying to mask part of a string using JavaScript.

eg. The mask of the second and third segments of a credit card number, for example, using regular expression:

  • 4567 6365 7987 37834567 **** **** 3783
  • 3457 732837 823723457 ****** 82372

I just want to keep the first 4 numbers and last 5 characters.

This is my first attempt: /(?!^.*)[^a-zA-Z\s](?=.{5})/g

https://regex101.com/r/ZBi54c/2

+4
source share
4 answers

You can try the following:

var cardnumber = '4567 6365 7987 3783';
var first4 = cardnumber.substring(0, 4);
var last5 = cardnumber.substring(cardnumber.length - 5);

mask = cardnumber.substring(4, cardnumber.length - 5).replace(/\d/g,"*");
console.log(first4 + mask + last5);
Run codeHide result
+2
source

The answer seems to satisfy the OP. Here is another solution using only Regexes:

function starry(match, gr1, gr2, gr3) {
  var stars = gr2.replace(/\d/g, '*');
  return gr1 + " " + stars + " " + gr3;
}

function ccStarry(str) {
  var rex = /(\d{4})\s(\d{4}\s\d{4}|\d{6})\s(\d{4}|\d{5})/;

  if (rex.test(str))
    return str.replace(rex, starry);
  else return "";
}


var s1 = "4567 6365 7987 3783";
var s2 = "3457 732837 82372";
var s3 = "dfdfdf";
console.log(ccStarry(s1));
console.log(ccStarry(s2));
console.log(ccStarry(s3));
Run codeHide result

. , . , , .

0

.

console.log(
    ['4567 6365 7987 3783', '3457 732837 82372'].map(
        s => s.slice(0, 4) + s.slice(4).replace(/\d(?=.* )/g, '*')
    )
);
Hide result
0

JavaScript, , , JS , , , , .

, .

, *, : ( PHP, )

$parts = explode(" ",$fullnumber);
$first = array_shift($parts);
$last = array_pop($parts);
$middle = implode(" ",$parts);
$mask = preg_replace("/\d/","*",$middle);
$result = "$first $mask $last";

*

-2

Source: https://habr.com/ru/post/1675277/


All Articles