替换textarea中的单词

时间:2017-03-08 19:02:35

标签: javascript jquery

我想在我的TEXTAREA中用****替换某些单词,但是这个脚本不起作用。谢谢你的帮助

<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>
<script>
var input = document.getElementById('Body')[0],
    output = document.getElementById('Body')[0],
    badwords = /\b(test|test2|test3)\b/g;

input.onkeyup = function () {
    output.innerHTML = this.value.replace(badwords, function (fullmatch, badword) {
        return '<sub>' + new Array(badword.length + 1).join('*') + '</sub>';
    });
};

input.onkeyup();
input.focus();
</script>

1 个答案:

答案 0 :(得分:0)

这是一个有效的解决方案,评论中有解释:

//remove [0].  getElementById returns an element, not a collection:
var input = document.getElementById('Body'),
    output = document.getElementById('Body'),
    badwords = /\b(test1|test2|test3)\b/g;

//addEventListener is the best way to add listeners:
input.addEventListener('keyup', function() {  

//Change innerHTML to value here:
  output.value = this.value.replace(badwords, function (fullmatch, badword) { 

//Remove '<sub>...</sub>'.  Textareas support text content only.
    return new Array(badword.length + 1).join('*');  
  });
});

input.focus();
<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>