如何检查字符串是否包含 JavaScript 中子字符串数组中的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5582574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a string contains text from an array of substrings in JavaScript?
提问by PercivalMcGullicuddy
Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
很直接。在 javascript 中,我需要检查一个字符串是否包含数组中保存的任何子字符串。
回答by T.J. Crowder
There's nothing built-in that will do that for you, you'll have to write a function for it.
没有任何内置功能可以为您做到这一点,您必须为它编写一个函数。
If you knowthe strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:
如果您知道字符串不包含任何正则表达式中的特殊字符,那么您可以作弊,如下所示:
if (new RegExp(substrings.join("|")).test(string)) {
// At least one match
}
...which creates a regular expression that's a series of alternationsfor the substrings you're looking for (e.g., one|two
) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*
, [
, etc.), you'd have to escape them first and you're better off just doing the boring loop instead.
...它创建了一个正则表达式,它是您正在寻找的子字符串的一系列交替(例如,one|two
)并测试是否有任何匹配项,但如果任何子字符串包含任何特殊字符在正则表达式(*
,[
等)中,您必须先转义它们,而最好只执行无聊的循环。
Live Example:
现场示例:
var substrings = ["one", "two", "three"];
var str;
// Setup
console.log("Substrings: " + substrings.join(","));
// Try it where we expect a match
str = "this has one";
if (new RegExp(substrings.join("|")).test(str)) {
console.log("Match using '" + str + "'");
} else {
console.log("No match using '" + str + "'");
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (new RegExp(substrings.join("|")).test(str)) {
console.log("Match using '" + str + "'");
} else {
console.log("No match using '" + str + "'");
}
In a comment on the question, Martinasks about the new Array.prototype.map
method in ECMAScript5. map
isn't all that much help, but some
is:
在对该问题的评论中,Martin询问了Array.prototype.map
ECMAScript5 中的新方法。map
没有那么多帮助,但是some
:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
Live Example:
现场示例:
var substrings = ["one", "two", "three"];
var str;
// Setup
console.log("Substrings: " + substrings.join(","));
// Try it where we expect a match
str = "this has one";
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
console.log("Match using '" + str + "'");
} else {
console.log("No match using '" + str + "'");
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
console.log("Match using '" + str + "'");
} else {
console.log("No match using '" + str + "'");
}
You only have it on ECMAScript5-compliant implementations, though it's trivial to polyfill.
你只在符合 ECMAScript5 的实现上有它,尽管 polyfill 是微不足道的。
Update in 2020: The some
example can be simpler with an arrow function (ES2015+), and you might use includes
rather than indexOf
:
2020 年更新:some
使用箭头函数(ES2015+)可以使示例更简单,您可以使用includes
而不是indexOf
:
if (substrings.some(v => str.includes(v))) {
// There's at least one
}
Live Example:
现场示例:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log("Substrings: " + substrings.join(","));
// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log("Match using '" + str + "'");
} else {
console.log("No match using '" + str + "'");
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log("Match using '" + str + "'");
} else {
console.log("No match using '" + str + "'");
}
Or even throw bind
at it, although for me the arrow function is much more readable:
甚至扔bind
它,虽然对我来说箭头函数更具可读性:
if (substrings.some(str.includes.bind(str))) {
// There's at least one
}
Live Example:
现场示例:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log("Substrings: " + substrings.join(","));
// Try it where we expect a match
str = "this has one";
if (substrings.some(str.includes.bind(str))) {
console.log("Match using '" + str + "'");
} else {
console.log("No match using '" + str + "'");
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(str.includes.bind(str))) {
console.log("Match using '" + str + "'");
} else {
console.log("No match using '" + str + "'");
}
回答by raveren
var yourstring = 'tasty food'; // the string to check against
var substrings = ['foo','bar'],
length = substrings.length;
while(length--) {
if (yourstring.indexOf(substrings[length])!=-1) {
// one of the substrings is in yourstring
}
}
回答by Praveena
One line solution
一条线解决方案
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false
if substring exists\does'nt exist
true\false
如果子字符串返回exists\does'nt exist
Needs ES6 support
需要 ES6 支持
回答by Jim Blackler
function containsAny(str, substrings) {
for (var i = 0; i != substrings.length; i++) {
var substring = substrings[i];
if (str.indexOf(substring) != - 1) {
return substring;
}
}
return null;
}
var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);
回答by kylewelsby
For people Googling,
对于谷歌搜索的人,
The solid answer should be.
肯定的答案应该是。
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
回答by user
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]
}
}
edit: If the order of the tests doesn't matter, you could use this (with only one loop variable):
编辑:如果测试的顺序无关紧要,您可以使用它(只有一个循环变量):
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]
}
}
回答by David Douglas
Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5somearray method and ES6arrow functions)
使用搜索字符串或搜索字符串数组搜索标签或关键字数组的 Javascript 函数。(使用ES5一些数组方法和ES6箭头函数)
// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
// array matches
if (Array.isArray(b)) {
return b.some(x => a.indexOf(x) > -1);
}
// string match
return a.indexOf(b) > -1;
}
Example usage:
用法示例:
var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
// 1 or more matches found
}
回答by Gintautas Miliauskas
If the array is not large, you could just loop and check the string against each substring individually using indexOf()
. Alternatively you could construct a regular expression with substrings as alternatives, which may or may not be more efficient.
如果数组不大,您可以使用indexOf()
. 或者,您可以使用子字符串作为替代构造一个正则表达式,这可能更有效,也可能无效。
回答by akinuri
Not that I'm suggesting that you go and extend/modify String
's prototype, but this is what I've done:
并不是我建议你去扩展/修改String
原型,但这就是我所做的:
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
回答by alavry
Drawing from T.J. Crowder's solution, I created a prototype to deal with this problem:
借鉴 TJ Crowder 的解决方案,我创建了一个原型来处理这个问题:
Array.prototype.check = function (s) {
return this.some((v) => {
return s.indexOf(v) >= 0;
});
};