18

I want to add a space between every 4 characters. I'm developing a webpage about credit card numbers.

example

var x = document.getElementById("card_number").value;

example : if the value of x is 1234567890123456

I need to split this number every 4 characters and add a space. Like this

1234 5678 9012 3456

and I need this number on a variable. Because I need to set this number on the textbox. Please help me. thanks

Antu
  • 2,197
  • 3
  • 25
  • 40
ChethiyaKD
  • 726
  • 2
  • 7
  • 13
  • Simular question like: https://stackoverflow.com/questions/1772941/how-can-i-insert-a-character-after-every-n-characters-in-javascript use the search function – episch Nov 22 '18 at 08:56
  • [Alternative search](https://www.google.nl/search?q=style+OR+format+credit+card+number+JavaScript+site%3Astackoverflow.com) – mplungjan Nov 22 '18 at 08:58

3 Answers3

38

You can use RegEx for this

const dummyTxt = '1234567890123456';

const joy = dummyTxt.match(/.{1,4}/g);
console.log(joy.join(' '));
8ctopus
  • 2,617
  • 2
  • 18
  • 25
lifeisbeautiful
  • 817
  • 1
  • 8
  • 18
14

You could look for four characters with a positive lookahead for more characters and insert a space after each block.

function format(s) {
    return s.toString().replace(/\d{4}(?=.)/g, '$& ');
}

console.log(format(1234567890123456));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
4

Without regex, you can use map as well to achieve this

let x = '1234567890123456'

let res = [...x].map((d, i) => (i) % 4 == 0 ? ' ' + d : d).join('').trim()

console.log(res)
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22