How to add spaces to a number every 4 digits in TypeScript

2 Answers

0 votes
const cardNumber: string = "7003125334556789";

const cardNumberWithSpaces: string = cardNumber.replace(/(.{4})/g, "$1 ");

console.log(cardNumberWithSpaces);

 
 
/*
run:
 
"7003 1253 3455 6789 "
 
*/

 



answered May 30, 2024 by avibootz
0 votes
const cardNumber: string = "7003125334556789";

const cardNumberWithSpaces: string[] = cardNumber.match(/.{1,4}/g);
 
console.log(cardNumberWithSpaces);
console.log(cardNumberWithSpaces.join(' '));

 
 
/*
run:
 
["7003", "1253", "3455", "6789"] 
"7003 1253 3455 6789" 
 
*/

 



answered May 31, 2024 by avibootz

Related questions

2 answers 146 views
2 answers 133 views
1 answer 145 views
1 answer 112 views
1 answer 121 views
1 answer 116 views
2 answers 135 views
...