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 153 views
2 answers 141 views
1 answer 150 views
1 answer 119 views
1 answer 126 views
1 answer 122 views
2 answers 144 views
...