我正在尝试在特定字符串中插入其他字符。
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 ; }
}
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sample(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
通过在htmlinput中使用
onchange
属性,代码可以完美运行。但这也可以与onkeypress
属性一起运行吗?如果输入值为1006,则结果应为10'06''。帮助。谢谢。 最佳答案
试试这个:
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;
}
}
<input id="txt" type="text" placeholder="onkeypress" onkeyup="sample(this)" value="" />
<br/>
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
关于javascript - 字符插入错误的字符串索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32986364/