使用a Stackoverflow answer to this question,我这样做是为了检查一个禁止字数组中是否存在消息中的任何单词
if ($.inArray(message, badwordsarray) !== -1){
console.log("bad word found")
}
这适用于以下示例
var message = "blah"
var badwordsarray = ["blah", "foo", "baz"]
if ($.inArray(message, badwordsarray) !== -1){
console.log("bad word found")
}
但是,如果消息长于1且包含空格,则不会检测到错误的单词。在此示例中,由于包含快乐
,因此未检测到坏词 var message = "happy blah"
var badwordsarray = ["blah", "foo", "baz"]
if ($.inArray(message, badwordsarray) !== -1){
console.log("bad word found")
}
在Javascript中扫描禁止单词的句子的最佳方法是什么?
答案 0 :(得分:3)
您需要对邮件字符串进行标记。
var message = "happy blah";
var badwordsarray = ["blah", "foo", "baz"];
var messageParts = message.split(" ");
$(messageParts).each(function(i, item){
if ($.inArray(item, badwordsarray) !== -1) {
console.log("bad word found:", item);
}
});
答案 1 :(得分:0)
RegExp救援!
var message = "happy blah";
var badwordsarray = ["blah", "foo", "baz"];
var containsBadWord = badwordsarray.some(function (word) {
return new RegExp('\\b' + word + '\\b').test(word);
});
if (containsBadWord) {
console.log("bad word found");
}
答案 2 :(得分:0)
另一个选择是创建一个for循环并迭代每个坏词。
var message = "happy blah"
var badwordsarray = ["blah", "foo", "baz"]
for(var i = 0; i < badwordsarray.length; i++) {
if(message.indexOf(badwordsarray[i]) !== -1) {
alert('bad word found');
// You could also set a boolean variable to true when a word is found
}
}