put dash after every n character during input from keyboard

后端 未结 3 1224
一个人的身影
一个人的身影 2021-01-28 02:33
$(\'.creditCardText\').keyup(function() {
  var foo = $(this).val().split(\"-\").join(\"\"); // remove hyphens
  if (foo.length > 0) {
    foo = foo.match(new RegExp(         


        
3条回答
  •  心在旅途
    2021-01-28 03:18

    Per further comments, the op clarified they need a fixed interval for when to insert dashes. In that case, there are several ways to implement it; I think regular expression would probably be the worst, in other words, overkill and overly complication solution.

    Some simpler options would be to create a new character array, and in a loop append character by character, adding a dash too every time you get to the index you want. This would probably be the easiest to write and grok after the fact, but a little more verbose.

    Or you could convert to a character array and use an 'insert into array at index'-type function like splice() (see Insert Item into Array at a Specific Index or Inserting string at position x of another string for some examples).

提交回复
热议问题