How to Add a Space Between Every Sequence of Four Characters (Like a Credit Card Number)

How to add a space between every sequence of four characters (like a credit card number)?

You can use str_split()

$card = "56A19E6D77828";
echo join(" ", str_split($card, 4));

Outputs:

56A1 9E6D 7782 8

How to Add space between every 4 characters in JavaScript?

You can use RegEx for this

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

How to insert space every 4 characters for IBAN registering?

The existing answers are relatively long, and they look like over-kill. Plus they don't work completely (for instance, one issue is that you can't edit previous characters).

For those interested, according to Wikipedia:

Permitted IBAN characters are the digits 0 to 9 and the 26 upper-case Latin alphabetic characters A to Z.

Here is a relatively short version that is similar to the existing answers:

document.getElementById('iban').addEventListener('input', function (e) {  e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();});
<label for="iban">iban</label><input id="iban" type="text" name="iban" />

android format edittext to display spaces after every 4 characters

You need to use TextWatcher to achieve visual purpose spaces.

And use any simply split string by space logic to join it back or loop through the entire string per character wise and eliminate (char) 32 from the string

How to make autospace after every 4 digit in React

Id create a state variable to hold the cc-number

const [ccNumber, setCcNumber] = useState("");

And set the ccNumber onChange of the input

<input type="text" value={ccNumber} onChange={formatAndSetCcNumber} />

And inside fn formatAndSetCcNumber I'd handle the logic

const formatAndSetCcNumber = e => {
const inputVal = e.target.value.replace(/ /g, ""); //remove all the empty spaces in the input
let inputNumbersOnly = inputVal.replace(/\D/g, ""); // Get only digits

if (inputNumbersOnly.length > 16) {
//If entered value has a length greater than 16 then take only the first 16 digits
inputNumbersOnly = inputNumbersOnly.substr(0, 16);
}

// Get nd array of 4 digits per an element EX: ["4242", "4242", ...]
const splits = inputNumbersOnly.match(/.{1,4}/g);

let spacedNumber = "";
if (splits) {
spacedNumber = splits.join(" "); // Join all the splits with an empty space
}

setCcNumber(spacedNumber); // Set the new CC number
};

Here is a demo

How can I use credit card numbers containing spaces?

My view is that any Web app that rejects a credit card number with spaces isn't doing its job. When you receive a credit card number, it's easy enough to do:

String ccNumber = ccNumber.replaceAll("[\\s-]+", "");

to remove spaces and dashes (some use those too). Then validate the result. You'll simply annoy your users if you force them to remove spaces you could just as easily do.

As for how to validate, well that depends on a lot of things, such as which Web framework you're using and what validation options you've chosen. Struts 1 for example might or might not use Apache Commons Validator whereas Spring MVC will (probably) use Spring validation and so on. So I can't tell you exactly how to validate but I can tell you what to validate.

The first thing is that a CC number with spaces should not be rejected. Most people will find:

4123 0987 8876 2939

much easier to read than:

4123098788762939

which is really important if the user misses or mistypes a digit and needs to find why his or her credit card number failed validation. The replaceAll() at the top of this post covers this situation.

The second thing is that you display the credit card number (even when some of the digits are replaced with X for security reasons) in the correct way. I suggest you read through Anatomy of Credit Card Numbers.

That page gives you the rules for the number of digits and the valid prefixes. A robust Web application will implement these so you can tell if a credit card number is invalid before you try and use it. It can take up to 30 seconds (or possibly more) to submit credit card details to a payment gateway so you shouldn't do it until you are sure as you can be that the payment will be accepted. To do otherwise is to provide a really bad user experience. There is every chance the user will give up if it fails 1-2 times rather than wait.

As for displaying them, that depends on the # of digits:

  • 16: 4 groups of 4 separated by a space;
  • 15: like an American Express card ie 4-6-5 with a space between each group;
  • 14: like a Diners Club card ie 4-6-4 with a space between each group;
  • 13: Never seen 13 but 4-5-4 or 4-4-5 or 5-4-4 (or possibly 3-3-3-4) springs to mind.

The credit card number should be verified according to the checksum algorithm mentioned in the page before submitting for processing as part of a standard validation routine. That page has a Java implementation of that routine.

Every website that accepts credit card payment should be doing all of the above as an absolute minimum or you're simply throwing away business as a percentage of your users get frustrated.

So the short version is two simple rules:

  1. Be as forgiving as possible with user input; and
  2. Do absolutely everything possible to validate credit card details prior to submission.

Credit card number format

Scrap my previous answer.

The reason that you can't have the space is because jQuery is performing a validation of sorts on the value you are trying to set. Space is not allowed in a number, and so it's clearing the value. The exact same thing happens when you enter a letter.

There is nothing stopping you (at least in Chrome) from entering letters into a <input type="number"> field. It's just not valid and AFAIK if you submit the form, that field will contain an empty value (haven't tested this).

How add separator to string at every N characters in swift?

Swift 5.2 • Xcode 11.4 or later

extension Collection {

func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
sequence(state: startIndex) { start in
guard start < endIndex else { return nil }
let end = index(start, offsetBy: maxLength, limitedBy: endIndex) ?? endIndex
defer { start = end }
return self[start..<end]
}
}

func every(n: Int) -> UnfoldSequence<Element,Index> {
sequence(state: startIndex) { index in
guard index < endIndex else { return nil }
defer { let _ = formIndex(&index, offsetBy: n, limitedBy: endIndex) }
return self[index]
}
}

var pairs: [SubSequence] { .init(unfoldSubSequences(limitedTo: 2)) }
}


extension StringProtocol where Self: RangeReplaceableCollection {

mutating func insert<S: StringProtocol>(separator: S, every n: Int) {
for index in indices.every(n: n).dropFirst().reversed() {
insert(contentsOf: separator, at: index)
}
}

func inserting<S: StringProtocol>(separator: S, every n: Int) -> Self {
.init(unfoldSubSequences(limitedTo: n).joined(separator: separator))
}
}

Testing

let str = "112312451"

let final0 = str.unfoldSubSequences(limitedTo: 2).joined(separator: ":")
print(final0) // "11:23:12:45:1"

let final1 = str.pairs.joined(separator: ":")
print(final1) // "11:23:12:45:1"

let final2 = str.inserting(separator: ":", every: 2)
print(final2) // "11:23:12:45:1\n"

var str2 = "112312451"
str2.insert(separator: ":", every: 2)
print(str2) // "11:23:12:45:1\n"

var str3 = "112312451"
str3.insert(separator: ":", every: 3)
print(str3) // "112:312:451\n"

var str4 = "112312451"
str4.insert(separator: ":", every: 4)
print(str4) // "1123:1245:1\n"


Related Topics



Leave a reply



Submit