Return 使用 jquery 在 keyup 上匹配来自 textarea 的文本

Return matching text from textarea on keyup using jquery

我有一个文本区域,我想监视该文本区域以获取预定义的键盘匹配单词或短语列表。我可以按如下方式实现,但我遇到的问题是为用户显示匹配的单词 and/or 短语。例如,如果用户键入 "test, test two",我将如何从 grep 语句中 return 显示那些匹配项(或通过其他方法)? - 即有一个 div 更新为 "Please avoid using the following words and/or phrases: test1, test two".

    function isBanned(array, name){
      return $.grep(array, function(i){
        return name.indexOf(i) >= 0;
      }).length > 0;
    }

    var bannedInput = ['test1','test two'];

    $('#eventText').keyup(function(){
      var inputVal = $('#eventText').val();

      var match = isBanned(bannedInput, inputVal.toLowerCase());

      if(match){
        alert("match found"); 
      }
    }); 

$.map 可能有帮助:

function isBanned(bannedWords, input){
  return $.map(bannedWords, function(n, i){
    return input.indexOf(n) >= 0 ? n : 0;
  }
}    

isBanned 将 return 一个数组,其中包含的条目要么是禁用词,要么是 0。然后您可以使用 $.grep 来获取在中找到的禁用词数组输入:

var filteredWords = isBanned(bannedInput, inputVal.toLowerCase());
var bannedWords = $.grep(filteredWords, function(n, i) {return n !== 0});

尝试

var input = $("#eventText"),
    output = $("[for=eventText]"),
    bannedInput = ["test1", "test two"];

input.on("keyup", function (e) {
    var name = e.target.value.toLowerCase()
    , match = $.grep(bannedInput, function (value) {
        return new RegExp(value).test(name)
    });
    if (!!match.length) {
        output.append(
          "<br />Please avoid using the following words and/or phrases: " 
          + "<span class=banned>\"" 
          + match.join(match.length === 1 ? " " : "\"<i>,</i> \"") 
          + "\"</span>")
    } else {
        output.empty()
    }
});

var input = $("#eventText"),
    output = $("[for=eventText]"),
    bannedInput = ["test1", "test two"];

input.on("keyup", function (e) {
    var name = e.target.value.toLowerCase()
    , match = $.grep(bannedInput, function (value) {
        return new RegExp(value).test(name)
    });
    if (!!match.length) {
        output.append(
          "<br />Please avoid using the following words and/or phrases: " 
          + "<span class=banned>\"" 
          + match.join(match.length === 1 ? " " : "\"<i>,</i> \"") 
          + "\"</span>")
    } else {
        output.empty()
    }
});
i {
    color:rgb(0, 0, 0);
}
.banned {
    color:rgb(0, 0, 255);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="eventText" /><output for="eventText"></output>