1
$('.creditCardText').keyup(function() {
  var foo = $(this).val().split("-").join(""); // remove hyphens
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
  }
  $(this).val(foo);
});

I found this tutorial on putting dash after every 4 character from here my question is what if the character interval is not constant like in this example it is only after every 4 what if the interval is 3 characters "-" 2 characters "-" 4 characters "-" 3 characters "-" so it would appear like this 123-12-1234-123-123.

Community
  • 1
  • 1
Brownman Revival
  • 3,620
  • 9
  • 31
  • 69
  • 1
    unrelated, but wont it be better if you could use something like http://digitalbush.com/projects/masked-input-plugin/ – naveen Jan 09 '15 at 02:27
  • @naveen i will check on it and see if its ok to use it..is it free? – Brownman Revival Jan 09 '15 at 02:29
  • 1
    yep. it is free till date. downvoter, care to elaborate on the downvote? – naveen Jan 09 '15 at 02:30
  • How do you propose to determine which interval will be used when? Is it regular, based on other data like white space or break characters – Jon Adams Jan 09 '15 at 02:45
  • @JonAdams lets say this is a fixed interval `123-12-1234-123-122` – Brownman Revival Jan 09 '15 at 02:49
  • @HogRider "Let's say..." If it is fixed that means one kind of soluation. If it's not, its a very different solution. Which do you really need? It sounds like you're not sure. – Jon Adams Jan 09 '15 at 02:52
  • 1
    @JonAdams Let me rephrase myself this is the fixed interval `123-12-1234-123-122` – Brownman Revival Jan 09 '15 at 02:53
  • What happens if the user wants to edit the existing value? If they try to type in the middle of the string that code will move the cursor back to the end of the string. – nnnnnn Jan 09 '15 at 03:07
  • @nnnnnn it will still move accordingly for example `123-12-1234-123-12` an i typed `0` between `12` it will move so it will become `102-31-2123-412-312` – Brownman Revival Jan 09 '15 at 03:23
  • You misunderstand. Yes, the hyphens will be moved to the correct places, but also the *cursor* will be moved to the end of the string such that the user would have to type the first digit they want to insert then use the mouse to click back next to it to type the second digit they want to insert, etc. And the arrow/home/etc. keys wouldn't work at all - after clicking any of those keys your code would move the cursor back to the end of the string. (Haven't you tried it for yourself?) – nnnnnn Jan 09 '15 at 03:32

4 Answers4

13

In this case, it is more convenient to just write normal code to solve the problem:

function format(input, format, sep) {
    var output = "";
    var idx = 0;
    for (var i = 0; i < format.length && idx < input.length; i++) {
        output += input.substr(idx, format[i]);
        if (idx + format[i] < input.length) output += sep;
        idx += format[i];
    }

    output += input.substr(idx);

    return output;
}

Sample usage:

function format(input, format, sep) {
    var output = "";
    var idx = 0;
    for (var i = 0; i < format.length && idx < input.length; i++) {
        output += input.substr(idx, format[i]);
        if (idx + format[i] < input.length) output += sep;
        idx += format[i];
    }

    output += input.substr(idx);

    return output;
}

$('.creditCardText').keyup(function() {
    var foo = $(this).val().replace(/-/g, ""); // remove hyphens
    // You may want to remove all non-digits here
    // var foo = $(this).val().replace(/\D/g, "");

    if (foo.length > 0) {
        foo = format(foo, [3, 2, 4, 3, 3], "-");
    }
  
    
    $(this).val(foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="creditCardText" />

While it is possible to do partial matching and capturing with regex, the replacement has to be done with a replacement function. In the replacment function, we need to determine how many capturing group actually captures some text. Since there is no clean solution with regex, I write a more general function as shown above.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
1

You can split it using a regular expression. In this case, I'm using a expression to check for non-spaces with interval 3-2-4-3.

The RegExp.exec will return with a "match" array, with the first element containing the actual string. After removing the first element of the match, you can then join them up with dashes.

var mystring = "123121234123"
var myRegexp = /^([^\s]{3})([^\s]{2})([^\s]{4})([^\s]{3})$/g
var match = myRegexp.exec(mystring);
if (match)
{
    match.shift();
    mystring = match.join("-")
    console.log(mystring)
}
maskie
  • 447
  • 4
  • 8
0

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

Community
  • 1
  • 1
Jon Adams
  • 24,464
  • 18
  • 82
  • 120
  • Sir i made an edit can you please check and see if the answer is still valid im so sorry i thought it is not relevant to put it but what i am asking for is when i type in when i get to 3rd character a dash will appear and so on.. – Brownman Revival Jan 09 '15 at 03:03
  • If you need this to be an interactive keyboard input validation, I recommend finding an appropriate validation jQuery plugin for whatever kind of number you're dealing with. StackOverflow doesn't usually answer questions with lists of possible libraries though. If you want to write it yourself, you can still do it with the loop options, you just need to check that dash characters are skipped when counting the index so it doesn't insert duplicate dashes. – Jon Adams Jan 09 '15 at 03:07
0

Pass the input value and the indexes to append the separator, first, it will remove the existing separators then just append separators on positions indexes.

export function addSeparators(
  input: string,
  positions: number[],
  separator: string
): string {
  const inputValue = input.replace(/-/g, '').split(''); // remove existing separators and split characters into array
  for (let i = 0; i < inputValue.length; i++) {
    if (positions.includes(i)) inputValue.splice(i, 0, separator);
  }
  return inputValue.join('');
}