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 3783
4567 **** **** 3783
3457 732837 82372
3457 ****** 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
/(?!^.*)[^a-zA-Z\s](?=.{5})/g
https://regex101.com/r/ZBi54c/2
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);
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));
. , . , , .
.
console.log( ['4567 6365 7987 3783', '3457 732837 82372'].map( s => s.slice(0, 4) + s.slice(4).replace(/\d(?=.* )/g, '*') ) );
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";
*
Source: https://habr.com/ru/post/1675277/More articles:Имеет смысл использовать PersistenceExceptionTranslationPostProcessor с Spring JdbcTemplate? - springHow to create an Entity structure built into a function for transforming an Sql server - entity-frameworkHow do I display the required user roles (access control information) in the Swagger interface for Spring endpoints? - springtools.build:gradle:2.3.1 infected with HEUR: Trojan.AndroidOS.Boogr.gsh - androidScala: wrong output type? - scalaClosing for UIGestureRecognizers - closuresUIGestureRecognizer with closure - ios#selector not compatible with closure? - closuresRace Status with Node.js and Firebase - javascriptKnex with Postgres keeps timestamp inadvertently - node.jsAll Articles