替换似乎没有在这个功能?

时间:2018-05-22 11:21:18

标签: jquery html

我正在尝试使用文本框来更改div中的文本,如果添加方括号,我希望在文本周围添加跨度以使文本变为绿色。到目前为止,这是我的代码:

function greenText() {
  var textAreaText = $('#textarea').val();
  var replacedText = textAreaText.replace("[", "<span style='color:green'>").replace("]", "</span>");
  $('#preview').html(replacedText);
}

$(function() {
  greenText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preview" style="height: 4em; background-color:#eee; padding:10px;"></div>
<textarea id="textarea" rows="4" cols="50" onchange="greenText();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
  At w3schools.com you will learn how to [make a website]. 
</textarea>

greenText函数在页面加载时有效,但是当我在括号中添加更新preview div时,它会将方括号打印到页面而不是span标记。有没有人知道为什么函数没有替换文本?

1 个答案:

答案 0 :(得分:1)

对于字符串内的多次替换,您需要使用RegEx

&#13;
&#13;
function greenText() {
  var textAreaText = $('#textarea').val();
  var replacedText = textAreaText.replace(/\[/g, "<span style='color:green'>").replace(/\]/g, "</span>");
  $('#preview').html(replacedText);
}

$(function() {
  greenText();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preview" style="height:400px; background-color:#eee; padding:40px;"></div>
<textarea id="textarea" rows="4" cols="50" onchange="greenText();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
  At w3schools.com you will learn how to [make a website]. 
</textarea>
&#13;
&#13;
&#13;

相关问题