How to check if a string contains text from an arr

2019-01-06 09:15发布

Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.

13条回答
Ridiculous、
2楼-- · 2019-01-06 09:53

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`
}
查看更多
叛逆
3楼-- · 2019-01-06 09:56

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.

Gratuitous live example


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:

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.)

查看更多
家丑人穷心不美
4楼-- · 2019-01-06 10:03

building on T.J Crowder's answer

using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.

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 ...'));

查看更多
神经病院院长
5楼-- · 2019-01-06 10:07

Using underscore.js or lodash.js, you can do the following on an array of strings:

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
查看更多
forever°为你锁心
6楼-- · 2019-01-06 10:08
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
   }
}
查看更多
放我归山
7楼-- · 2019-01-06 10:08
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);
查看更多
登录 后发表回答