4

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
2
  • A regex? RegExp(strings.join('|')).test(myString) 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 Commented Sep 22, 2017 at 12:18

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

hi andy thanks but i still have some difficulty grasping regex, so was actually looking for a simple to remember solution.
2

I think it will be simple and pretty fast:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.