admin管理员组

文章数量:1295939

I need to check if any of a set of strings exists in one main string.

Currently I'm using an array with a for loop to check each string.

Is there a simpler way, like this solution for ruby which I've e across on - How to pare a string against multiple other strings

["string1","string2","string3"].include? myString

I need to check if any of a set of strings exists in one main string.

Currently I'm using an array with a for loop to check each string.

Is there a simpler way, like this solution for ruby which I've e across on - How to pare a string against multiple other strings

["string1","string2","string3"].include? myString
Share Improve this question edited May 23, 2017 at 11:58 CommunityBot 11 silver badge asked Aug 17, 2013 at 23:54 Ranjit ChawlaRanjit Chawla 632 silver badges5 bronze badges 2
  • A regex? RegExp(strings.join('|')).test(myString) – elclanrs Commented Aug 17, 2013 at 23:56
  • unfortunately with this string19 will return true for string1 but this works : matchfound = RegExp("^(" +strings.join("|")+")$").test(myString); basically checking against ^(string1|string2|string3)$ instead of string1|string2|string3 – Ranjit Chawla Commented Sep 22, 2017 at 12:18
Add a ment  | 

3 Answers 3

Reset to default 4

How plex is your for loop? This is what loops exist for. Assuming your set of strings are an array called setOfStrings and your main string is in a variable called mainString:

var stringExists = false;
var setOfStrings = ['string1', 'string2', 'string3'];

for(var i =0;i < setOfStrings.length; i++){
  if(mainString.indexOf(setOfStrings[i]) != -1)
      stringExists = true;
}

It might not be as terse as your Ruby construct, but it's pretty darned mon.

A did a little experiment and found that the following worked fine. The only overhead is the generation of the regexps for each element of the array. If check is zero or above, one of the strings was found.

if (!('included' in Array.prototype)) {
  Array.prototype.included = function() {
    return arr.map(function (item) {
      var regex = new RegExp(item, 'g');
      if (regex.test(str)) return true;
      return false;
    }).indexOf(true);
  };
}

To return a boolean instead of a number just change it to:

if (!('included' in Array.prototype)) {
  Array.prototype.included = function () {
    var regex, found = false;
    for (var i = 0, l = this.length; i < l; i++) {
      regex = new RegExp(this[i], 'g');
      if (regex.test(str)) { found = true; break; }
    }
    return found;
  };
}

var found = arr.included(str);

This is an edit of my previous answer because I realised I hadn't actually answered the question :)

I think it will be simple and pretty fast:

const arrayOfStrings = ["string1","string2","string3"];
const myStringExists = arrayOfStrings.some(item => myString.includes(item));

本文标签: javascriptCheck if any of multiple strings exist in a stringStack Overflow