如何在jquery中使用keyup事件生成破折号(“-”)?

如何在jquery中使用keyup事件生成破折号(“-”)?,jquery,Jquery,我试图在jquery中使用keyup事件创建一个类似于“12-1234-12-12-12345-123”的帐号 我试过这个。它适用于每两个字符。但我的情况有点不同。我的案例不是每两个字符一个。我必须像这样划一个破折号(“-”)12-1234-12-12-12345-123 我试过下面的代码 $('#ContentPlaceHolder1_txtAccount1').keyup(function () { console.log("key press working"); var

我试图在jquery中使用keyup事件创建一个类似于“12-1234-12-12-12345-123”的帐号

我试过这个。它适用于每两个字符。但我的情况有点不同。我的案例不是每两个字符一个。我必须像这样划一个破折号(“-”)12-1234-12-12-12345-123

我试过下面的代码

$('#ContentPlaceHolder1_txtAccount1').keyup(function () {
    console.log("key press working");
    var foo = $(this).val().split("-").join(""); // remove hyphens

    var accSplit = $(this).val().split("-");
    if (accSplit.length == 0) {
        if (foo.length > 0) {
            foo = foo.match(new RegExp('.{1,2}', 'g')).join("-");
        }
    }
    if (accSplit.length == 1) {
        if (foo.length > 0) {
            foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
        }
    }
    $(this).val(foo);
});

这是我的版本,在数组中有预定义的位置映射,然后根据此数组位置添加“-”

$('#ContentPlaceHolder1_txtAccount1').keyup(function () {
console.log("key press working");
var foo = $(this).val(); // Get Current Text Box Value
var hyphenPos=[3,8,11,14,20]//12-1234-12-12-12345-123 mapping hyphen positions
if($.inArray(foo.length,hyphenPos)>-1) // Check if we need to add hyphen
{
  var beforeHyphen=foo.substr(0,foo.length-1); // substring except last character
  var lastcharacter=foo.substr(foo.length-1,1); // last character
  var finalString=beforeHyphen+'-'+lastcharacter; // final result
  $(this).val(finalString); // show 
}

}))

这是我的版本,在数组中有预定义的位置映射,然后根据此数组位置添加“-”

$('#ContentPlaceHolder1_txtAccount1').keyup(function () {
console.log("key press working");
var foo = $(this).val(); // Get Current Text Box Value
var hyphenPos=[3,8,11,14,20]//12-1234-12-12-12345-123 mapping hyphen positions
if($.inArray(foo.length,hyphenPos)>-1) // Check if we need to add hyphen
{
  var beforeHyphen=foo.substr(0,foo.length-1); // substring except last character
  var lastcharacter=foo.substr(foo.length-1,1); // last character
  var finalString=beforeHyphen+'-'+lastcharacter; // final result
  $(this).val(finalString); // show 
}

}))

不确定这是否是最好的方法,但它确实创建了您要查找的字符串。考虑以下事项:

$(函数(){
函数splitVal(v,a){
var-str=[];
如果(a==未定义){
a=[2,4,2,2,5,3];
}
var val=“”+v.split(“-”)。join(“”);
var vl=val长度;
变量i=a[0],j=i+a[1],k=j+a[2],l=k+a[3],m=l+a[4],n=m+a[5];
控制台日志(val,vl);
开关(真){

案例VL

不确定这是否是最好的方法,但它确实创建了你要寻找的字符串。考虑以下内容:

$(函数(){
函数splitVal(v,a){
var-str=[];
如果(a==未定义){
a=[2,4,2,2,5,3];
}
var val=“”+v.split(“-”)。join(“”);
var vl=val长度;
变量i=a[0],j=i+a[1],k=j+a[2],l=k+a[3],m=l+a[4],n=m+a[5];
控制台日志(val,vl);
开关(真){

case vl您的代码正在运行,您能帮我处理backspace吗?如果用户想更改,它运行得不好。您可以用back尝试一次space@Twusty当用户按Backspace键时,不应执行此操作,只需按最后一个破折号“-”当我按下后退按钮时,它不工作space@Liamneesan不客气。我对代码进行了一些更新,以允许可调整的格式。您的代码正在运行,您可以帮助我使用backspace吗?如果用户想要更改,它运行不好。您可以使用back尝试一次space@Twusty当用户按Backspace键时,不应执行此操作,只需按最后一个破折号“-”当我按下后退按钮时,它不工作space@Liamneesan不客气。我对代码进行了一些更新,允许调整格式。