示例:
如果主要输入值是这样的“1+23+”那么 我需要用新的特殊字符替换最后一个特殊字符 假设我单击新的特殊字符,例如减号、乘号和除号等。
我的预期输出:
- 当我点击减号时>“1+23-”
- 当我点击乘号时>“1+23*”
<body>
<input type="text" id="Main">
<input class="ip" type="button" value="1" onclick="Cal(this)">
<input class="ip" type="button" value="2" onclick="Cal(this)">
<input class="ip" type="button" value="3" onclick="Cal(this)">
<input class="ip" type="button" value="+" onclick="Cal(this)">
<input class="ip" type="button" value="-" onclick="Cal(this)">
<input class="ip" type="button" value="*" onclick="Cal(this)">
</body>
<script>
function Cal(btn)
{
document.getElementById("Main").value+=btn.value;
}
</script>
最佳答案
这就是你想要的。我首先使用正则表达式检测特殊字符来测试输入字符串的最后一个字符,如果输入中有特殊字符,并且您按下的按钮的值也是特殊字符,我会从字符串。然后在最后,您按下的按钮的值将附加到字符串的末尾。
function cal(btn)
{
let format = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
let input = document.getElementById("Main").value
if(format.test(input.charAt(input.length - 1)) && format.test(btn.value)){
input = input.slice(0, -1)
}
input += btn.value;
document.getElementById("Main").value = input
}
<body>
<input type="text" id="Main">
<input class="ip" type="button" value="1" onclick="cal(this)">
<input class="ip" type="button" value="2" onclick="cal(this)">
<input class="ip" type="button" value="3" onclick="cal(this)">
<input class="ip" type="button" value="+" onclick="cal(this)">
<input class="ip" type="button" value="-" onclick="cal(this)">
<input class="ip" type="button" value="*" onclick="cal(this)">
</body>
您可以编辑正则表达式以满足您的具体需求。
关于javascript - 当我在javascript中按下新字符时如何替换最后一个特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69504825/