Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
很直接。在javascript中,我需要检查字符串是否包含数组中的任何子字符串。
12 个解决方案
#1
116
There's nothing built-in that will do that for you, you'll have to write a function for it.
没有什么内置的东西可以帮你,你需要为它写一个函数。
If you know the 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 alternations for 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.
…这创建一个正则表达式的一系列交替子你在寻找(例如,1 | 2)和测试是否有匹配的,但如果任何特殊的子字符串包含任何字符的regex(*,等等),你不得不逃离他们,你最好做无聊的循环。
免费的活例子
Update:
更新:
In a comment on the question, Martin asks about the new Array#map
function in ECMAScript5. map
isn't all that much help, but some
is:
在对这个问题的评论中,Martin询问了ECMAScript5中新的数组#map函数。地图并没有多大的帮助,但有些是:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
Live example (Only works on modern browsers)
实时示例(仅适用于现代浏览器)
Mind you, it does mean some overhead, and you only have it on ECMAScript5-compliant implementations (so, not IE7 or earlier, for instance; maybe not even IE8), but still if you're really into that style of programming... (And you could use an ECMAScript5 shim, this one or any of several others.)
请注意,它确实意味着一些开销,并且您只在ecmascript5兼容的实现上使用它(例如,没有IE7或更早的版本);也许连IE8都没有,但如果你真的喜欢那种编程风格……(您可以使用ECMAScript5 shim,这一个或其他几个shim中的任何一个)。
#2
40
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
}
}
#3
16
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);
#4
10
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`
}
#5
6
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]
}
}
#6
5
One line solution
一行的解决方案
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false
if substring exists\does'nt exist
返回true\false(如果子字符串存在)\不存在
Needs ES6 support
需要ES6支持
#7
2
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()对每个子字符串进行循环和检查。或者,您可以构造一个正则表达式,使用子字符串作为替代,这可能更有效,也可能不更有效。
#8
2
Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)
Javascript函数,使用搜索字符串或搜索字符串数组搜索标记或关键字数组。(使用ES5 some array method和ES6 arrow function)
// 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
}
#9
0
Using underscore.js or lodash.js, you can do the following on an array of strings:
使用下划线。js或lodash。js,你可以对字符串数组做如下操作:
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];
var filters = ['Bill', 'Sarah'];
contacts = _.filter(contacts, function(contact) {
return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});
// ['John']
And on a single string:
在一根弦上
var contact = 'Billy';
var filters = ['Bill', 'Sarah'];
_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });
// true
#10
0
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()
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
#11
0
This is super late, but I just ran into this problem. In my own project I used the following to check if a string was in an array:
这太迟了,但我遇到了这个问题。在我自己的项目中,我使用下面的代码检查字符串是否在数组中:
["a","b"].includes('a') // true
["a","b"].includes('b') // true
["a","b"].includes('c') // false
This way you can take a predefined array and check if it contains a string:
这样,您就可以使用预定义的数组,并检查它是否包含字符串:
var parameters = ['a','b']
parameters.includes('a') // true
#12
0
building on T.J Crowder's answer
基于T。J克劳德的回答
using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.
使用转义RegExp测试至少一个子字符串的“至少一次”发生。
function buildSearch(substrings) {
return new RegExp(
substrings
.map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
.join('{1,}|') + '{1,}'
);
}
var pattern = buildSearch(['hello','world']);
console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));
#1
116
There's nothing built-in that will do that for you, you'll have to write a function for it.
没有什么内置的东西可以帮你,你需要为它写一个函数。
If you know the 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 alternations for 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.
…这创建一个正则表达式的一系列交替子你在寻找(例如,1 | 2)和测试是否有匹配的,但如果任何特殊的子字符串包含任何字符的regex(*,等等),你不得不逃离他们,你最好做无聊的循环。
免费的活例子
Update:
更新:
In a comment on the question, Martin asks about the new Array#map
function in ECMAScript5. map
isn't all that much help, but some
is:
在对这个问题的评论中,Martin询问了ECMAScript5中新的数组#map函数。地图并没有多大的帮助,但有些是:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
Live example (Only works on modern browsers)
实时示例(仅适用于现代浏览器)
Mind you, it does mean some overhead, and you only have it on ECMAScript5-compliant implementations (so, not IE7 or earlier, for instance; maybe not even IE8), but still if you're really into that style of programming... (And you could use an ECMAScript5 shim, this one or any of several others.)
请注意,它确实意味着一些开销,并且您只在ecmascript5兼容的实现上使用它(例如,没有IE7或更早的版本);也许连IE8都没有,但如果你真的喜欢那种编程风格……(您可以使用ECMAScript5 shim,这一个或其他几个shim中的任何一个)。
#2
40
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
}
}
#3
16
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);
#4
10
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`
}
#5
6
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]
}
}
#6
5
One line solution
一行的解决方案
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false
if substring exists\does'nt exist
返回true\false(如果子字符串存在)\不存在
Needs ES6 support
需要ES6支持
#7
2
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()对每个子字符串进行循环和检查。或者,您可以构造一个正则表达式,使用子字符串作为替代,这可能更有效,也可能不更有效。
#8
2
Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)
Javascript函数,使用搜索字符串或搜索字符串数组搜索标记或关键字数组。(使用ES5 some array method和ES6 arrow function)
// 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
}
#9
0
Using underscore.js or lodash.js, you can do the following on an array of strings:
使用下划线。js或lodash。js,你可以对字符串数组做如下操作:
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];
var filters = ['Bill', 'Sarah'];
contacts = _.filter(contacts, function(contact) {
return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});
// ['John']
And on a single string:
在一根弦上
var contact = 'Billy';
var filters = ['Bill', 'Sarah'];
_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });
// true
#10
0
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()
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
#11
0
This is super late, but I just ran into this problem. In my own project I used the following to check if a string was in an array:
这太迟了,但我遇到了这个问题。在我自己的项目中,我使用下面的代码检查字符串是否在数组中:
["a","b"].includes('a') // true
["a","b"].includes('b') // true
["a","b"].includes('c') // false
This way you can take a predefined array and check if it contains a string:
这样,您就可以使用预定义的数组,并检查它是否包含字符串:
var parameters = ['a','b']
parameters.includes('a') // true
#12
0
building on T.J Crowder's answer
基于T。J克劳德的回答
using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.
使用转义RegExp测试至少一个子字符串的“至少一次”发生。
function buildSearch(substrings) {
return new RegExp(
substrings
.map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
.join('{1,}|') + '{1,}'
);
}
var pattern = buildSearch(['hello','world']);
console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));