javascript - 当我在javascript中按下新字符时如何替换最后一个特殊字符

标签 javascript html jquery

示例:

如果主要输入值是这样的“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/

相关文章:

javascript - React.js - 每个页面的动态规范 url

javascript - 简单的响应式 html(带有可选的下拉菜单和 float 导航)

javascript - 在exceljs中插入一列

image - 在 canvas.toDataUrl ('image/jpeg' 、0.2) 上出现错误

jquery css 背景图像仅适用于 firefox

javascript - 选择 &lt;script&gt;...&lt;/script&gt; 的内容作为 html 正文中的纯文本?

PHP array_sum 输出单个数字而不是整体

html - 使用 VBScript 捕获 HTA 窗口关闭事件

javascript - 剑道网格 : Drag and Drop Cell Data From One Grid Into another

javascript - AJAX + Rails 的最新技术是什么?