Ranjit Chawla
Ranjit Chawla

Reputation: 63

Check if any of multiple strings exist in a string

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 come across on - How to compare a string against multiple other strings

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

Upvotes: 4

Views: 6559

Answers (3)

drazewski
drazewski

Reputation: 2017

I think it will be simple and pretty fast:

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

Upvotes: 2

Mister Epic
Mister Epic

Reputation: 16723

How complex 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 common.

Upvotes: 4

Andy
Andy

Reputation: 63524

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

Upvotes: 2

Related Questions