Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add space between every 4 characters in JavaScript? [duplicate]

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

like image 305
ChethiyaKD Avatar asked Nov 22 '18 08:11

ChethiyaKD


People also ask

How do you add a gap in JavaScript?

To add a space between characters of a string, call the split() method on the string to get a character array, then call the join() method on the array to join the characters with a space separator.

How do you put a space after 4 characters in HTML input?

CSS text-indent For example, to add an indent of 4 spaces, apply the rule text-indent: 4em; to the element.


3 Answers

You can use RegEx for this

let dummyTxt='1234567890123456';

let joy=dummyTxt.match(/.{1,4}/g);
console.log(joy.join(' '));
like image 94
lifeisbeautiful Avatar answered Oct 08 '22 20:10

lifeisbeautiful


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)
like image 27
Nitish Narang Avatar answered Oct 08 '22 20:10

Nitish Narang


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));
like image 13
Nina Scholz Avatar answered Oct 08 '22 18:10

Nina Scholz