javascript - 使用 Javascript 将字符串中的多个加号 (+) 替换为单个加号 (+)
问题描述
在以下代码中,我尝试使用 Javascript 将字符串中的多个加号替换为单个加号。我没有得到正确的正则表达式,请帮忙!
示例:This+is+my+++++text --> This+is+my+text
代码:
function doThis(){
document.getElementById("result").value = document.getElementById("TextInput").value.replace(/++/g,'+');
}
<html>
<head>
</head>
<body>
<textarea type="number" autocomplete="off" cols="30" id="TextInput" name="message" rows="10" style="width: 100%;">This++is+my+++++text</textarea><br><br>
<input class="button" type="button" value="Press" onclick="doThis()"><br/><br/>
Result: <input type="text" id="result">
</body>
</html>
解决方案
你需要逃避+
.
function doThis() {
document.getElementById("result").value =
document.getElementById("TextInput").value.replace(/\++/g, '+');
}
<textarea type="number" autocomplete="off" cols="30" id="TextInput" name="message" rows="10" style="width: 100%;">This++is+my+++++text</textarea><br><br>
<input class="button" type="button" value="Press" onclick="doThis()"><br/><br/> Result: <input type="text" id="result">
推荐阅读
- javascript - 一次查询,多个日期范围
- angular - ViewChild 升级到 Angular 9 后无法正常工作
- c++ - 每次返回双精度数组的元素时输出相同
- python - 我想使用 Python 脚本自动化 AS400 应用程序,例如登录到应用程序并选择一些选项
- css - 基于包装父类的样式规则
- python - 列出根画布中的所有进程组
- reactjs - react-images 为什么灯箱默认显示并失去其作为导入的样式
- python - 使用 python 连接到 postgre 的问题(在 pg_hba.conf 中)
- powershell - Powershell:如何请求用户身份验证以继续
- javascript - Ajax 调用引发 Invalid Character 错误