Javascript 格式化HTML输入文本产品密钥

Javascript 格式化HTML输入文本产品密钥,javascript,html,input,format,Javascript,Html,Input,Format,我在一个为Windows7/8创建无人参与的XML文件的网站上工作 我做了一个“产品密钥”文本输入,用户可以在其中输入他们的产品密钥,并将其添加到XML中,这样他们在安装过程中就不会收到提示 这就是我到目前为止所做的: <td>Product Key:</td> <td><input id="ProductKey1" size="5" maxlength="5" type="text">-<input id="ProductKey2" max

我在一个为Windows7/8创建无人参与的XML文件的网站上工作

我做了一个“产品密钥”文本输入,用户可以在其中输入他们的产品密钥,并将其添加到XML中,这样他们在安装过程中就不会收到提示

这就是我到目前为止所做的:

<td>Product Key:</td>
<td><input id="ProductKey1" size="5" maxlength="5" type="text">-<input id="ProductKey2" maxlength="5" size="5" type="text">-<input id="ProductKey3" maxlength="5" size="5" type="text">-<input id="ProductKey4" maxlength="5" size="5" type="text">-<input id="ProductKey5" maxlength="5" size="5" type="text"></td>
产品密钥:
----
我基本上添加了5个文本输入,最大长度为5个字符,每个字段用“-”分隔


我想做的是为产品密钥提供一个更长的字段,并让它在每5个字符后插入“-”。用javascript实现这一点最简单的方法是什么?

您可以模拟破折号,将其放在输入字段上,并添加onkeyup控件以添加空格,或者jquery.maskedinput:

有很多方法可以实现这一点。但我要做的是每隔5个字符对字符串进行“substr”。我会这样做:

function split_product_key(t) {
    // How many characters in string
    var length = t.length;
    // How many "5 chars length strings" is there in your string
    var loop = Math.ceil(length/5);
    // Create the output.
    var output = '';
    for (var i =1; i<=loop; i++) {
        // Getting the 5 chars substr
        output += t.substr((i*5),5) + '-';
    }
    // Removing the last "-"
    output = output.substr(0, output.length-1);
    return output;
}
功能拆分产品密钥(t){
//字符串中有多少个字符
变量长度=t.长度;
//您的字符串中有多少个“5字符长度字符串”
变量循环=数学单元(长度/5);
//创建输出。
var输出=“”;
对于(var i=1;i
这篇文章使用正则表达式使16位字符串看起来像“NLEB-8KPR-RZR1-QWJF”,编辑正则表达式部分以更改模式。此外,这是一篇旧文章,但我搜索了一个简单的解决方案,就是它。

您尝试了什么吗?
function split_product_key(t) {
    t = t.toUpperCase();
    var key = t.replace(/([\w]{4})([\w]{4})([\w]{4})([\w]{4})/, function(match, p1, p2, p3, p4, offset, string){
        return [p1, p2, p3, p4].join('-');
    });
    return key;
}