首页 > 解决方案 > 使用 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>

标签: javascripthtmlregexreplace

解决方案


你需要逃避+.

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">


推荐阅读