非常直截了当。在javascript中,我需要检查字符串是否包含数组中持有的任何子字符串。
当前回答
我并不是建议你去扩展/修改String的原型,但这是我所做的:
String.prototype.includes ()
String.prototype.includes = function (includes) { console.warn("String.prototype.includes() has been modified."); return function (searchString, position) { if (searchString instanceof Array) { for (var i = 0; i < searchString.length; i++) { if (includes.call(this, searchString[i], position)) { return true; } } return false; } else { return includes.call(this, searchString, position); } } }(String.prototype.includes); console.log('"Hello, World!".includes("foo");', "Hello, World!".includes("foo") ); // false console.log('"Hello, World!".includes(",");', "Hello, World!".includes(",") ); // true console.log('"Hello, World!".includes(["foo", ","])', "Hello, World!".includes(["foo", ","]) ); // true console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false
其他回答
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
编辑: 如果测试的顺序不重要,你可以使用这个(只有一个循环变量):
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
如果您正在处理一长串子字符串,这些子字符串由空格或任何其他常见字符分隔的完整“单词”组成,那么您可以在搜索中使用一些聪明的方法。
首先把你的字符串分成X组,然后X+1,然后X+2,…X和Y应分别为子字符串中单词最少和最多的单词数。例如,如果X是1,Y是4,“Alpha Beta Gamma Delta”变成:
"阿尔法" "贝塔" "伽马" "德尔塔"
"阿尔法·贝塔" "贝塔·伽马" "伽马·德尔塔"
"Alpha Beta Gamma" "Beta Gamma Delta"
"Alpha Beta Gamma Delta"
如果X是2 Y是3,那么你可以省略第一行和最后一行。
现在,如果您将它插入到Set(或Map)中,就可以快速搜索这个列表,比字符串比较快得多。
缺点是你不能搜索像“ta Gamm”这样的子字符串。当然,你可以通过按字符而不是按单词进行分割来实现这一点,但这样你通常需要构建一个庞大的Set,并且这样做所花费的时间/内存超过了好处。
你可以这样检查:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var list = ["bad", "words", "include"]
var sentence = $("#comments_text").val()
$.each(list, function( index, value ) {
if (sentence.indexOf(value) > -1) {
console.log(value)
}
});
});
</script>
</head>
<body>
<input id="comments_text" value="This is a bad, with include test">
</body>
</html>
单线解决方案
substringsArray.some(substring=>yourBigString.includes(substring))
如果子字符串存在\不存在,则返回true\false
需要ES6支持
如果数组不大,可以使用indexOf()循环并逐个检查每个子字符串。或者,您可以构造一个带有子字符串作为替代的正则表达式,这可能更有效,也可能不更有效。