22

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

2

3 Answers 3

41

You can use RegEx for this

const dummyTxt = '1234567890123456';

const joy = dummyTxt.match(/.{1,4}/g);
console.log(joy.join(' '));

Sign up to request clarification or add additional context in comments.

2 Comments

It do not add a space, it split it up
Yes, @GrégoryNEUT I have edited my answer now.
16

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));

1 Comment

Btw, isn't replace(/\w... better because IBANs sometimes start with FR or alike.
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)

1 Comment

It shows values with space like above. but not working in the insert input value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.