0

I'd like to search a string for multiple strings, and return true if it finds any of them in there, false otherwise, something like this:

var s = "thing1 thing2"
s.contains(["thing1","thing44444"]) // true
s.contains("1") // true
s.contains("x") // false

Here's what I have so far, but it's getting messier and doesn't really work:

String.prototype.contains = function(xv) {
    var t = this
    if(xv.isString()){ // isString/isArray are functions I made elsewhere in my code, they work.
        if(t.indexOf(xv) > -1)
            return true;
    } else if(xv.isArray()) {
        if(xv.contains(t)){
            return true
        }
        for(v in xv){
            if(t.indexOf(xv[v]) > -1){
                return true
            }
        }
    } else {
        return false
    }
}

As of now, it will return undefined if it makes it through the for loop without finding anything. I had return false after the for loop, but it would run before the for finished.

I feel like there's gotta be an easier way to do this.

I've already tried How do you search multiple strings with the .search() Method? but I couldn't send an array to .search().

Frameworks I'm using: angular 1.5.8, jquery 1.11.1

Community
  • 1
  • 1
Travis Heeter
  • 13,002
  • 13
  • 87
  • 129
  • "I had return false after the for loop, but it would run before the for finished." this isn't possible given the code in your example. – zzzzBov Nov 08 '16 at 20:02
  • You may wish to rethink altering the prototype of built in objects, or at least make sure you're polyfilling correctly. See also [Why is extending native objects a bad practice?](http://stackoverflow.com/q/14034180/215552). For instance [`Array.isArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) is already a function in recent versions of JavaScript, and Angular already has [`angular.isString()`](https://docs.angularjs.org/api/ng/function/angular.isString)... – Heretic Monkey Nov 08 '16 at 20:07
  • @MikeMcCaughan from the first answer you quoted: "Changing the behaviour of an object that will only be used by your own code is fine." I do appreciate the references though. Lots of good info here. Thanks brother. – Travis Heeter Nov 11 '16 at 21:09

1 Answers1

4

You can use Array.some and String.indexOf or String.includes

var s1 = "thing1 thing2";
var s2 = "Hello Kitty";

var r1 = ["thing1","thing44444"].some( x => s1.includes(x));
var r2 = ["Travis","Heeeeeeter"].some( x => s2.includes(x));

console.log(r1, r2); // true, false
adeneo
  • 312,895
  • 29
  • 395
  • 388