put dash after every n character during input from keyboard

后端 未结 3 1225
一个人的身影
一个人的身影 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:21

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

提交回复
热议问题