gpt4 book ai didi

javascript - 在字符串的错误索引中插入的字符

转载 作者:太空狗 更新时间:2023-10-29 15:49:12 24 4
gpt4 key购买 nike

我正在尝试在特定字符串中插入其他字符。

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''。帮助。谢谢。

最佳答案

试试这个:

You need to replace the quotes('/") before manipulating the string. Also use keyup event. Refer this to understand the purpose of each events. onkeyup is fired when the key is released

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com