Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask a portion of a String using RegExp

I'm trying to mask a portion of a string using JavaScript.

e.g. Mask second and third segment of credit-card number like this using regex:

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

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

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

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

like image 891
Josue Soriano Avatar asked Apr 20 '17 16:04

Josue Soriano


2 Answers

You can try this:

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);
like image 122
Tony Avatar answered Sep 23 '22 06:09

Tony


You could slice the first four digits and apply a replacement for the rest.

console.log(
    ['4567 6365 7987 3783', '3457 732837 82372'].map(
        s => s.slice(0, 4) + s.slice(4).replace(/\d(?=.* )/g, '*')
    )
);
like image 37
Nina Scholz Avatar answered Sep 23 '22 06:09

Nina Scholz