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
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.
CSS text-indent For example, to add an indent of 4 spaces, apply the rule text-indent: 4em; to the element.
You can use RegEx for this
let dummyTxt='1234567890123456';
let joy=dummyTxt.match(/.{1,4}/g);
console.log(joy.join(' '));
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)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With