插入字符串错误索引的字符

eir*_*jel 5 html javascript

我试图在特定的字符串中插入其他字符.

function sample(x) {
            if (x.value.length > 2 && x.value.length < 5) { 
                var first = x.value.substring(0, 2) + "'";
                var second = x.value.substring(2, x.value.length) + "''";
                x.value = first + "" + second ; }           
}
Run Code Online (Sandbox Code Playgroud)
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sample(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
Run Code Online (Sandbox Code Playgroud)

通过onchange在htmlinput中使用属性,代码运行完美.但这也可以用onkeypress属性运行吗?如果输入值为1006,则结果应为10'06''.救命.谢谢.

Ray*_*yon 3

尝试这个:

您需要quotes('/")在操作字符串之前替换 。也使用keyup事件。请参阅此内容以了解每个事件的目的。onkeyup释放按键时触发

function sample(x) {
  x.value = x.value.replace(/[\'\"]/g, '');
  if (x.value.length > 2 && x.value.length < 5) {
    var first = x.value.substring(0, 2) + "'";
    var second = x.value.substring(2, x.value.length) + "''";
    x.value = first + "" + second;
  }
}
Run Code Online (Sandbox Code Playgroud)
<input id="txt" type="text" placeholder="onkeypress" onkeyup="sample(this)" value="" />
<br/>
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
Run Code Online (Sandbox Code Playgroud)