如何在字符串中查找字符串数组? [英] How to find an array of strings in a string?

查看:128
本文介绍了如何在字符串中查找字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个字符串中搜索多个字符串,如果在其中找到它们中的任何一个,则返回true,否则返回false,如下所示:

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
    }
}

到目前为止,如果它通过for循环而不找到任何内容,它将返回undefined.我在for循环之后使用了return false,但是它将在for完成之前运行.

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.

我已经尝试过如何搜索.search()方法添加多个字符串?,但是我无法将数组发送到.search().

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

我正在使用的框架:angular 1.5.8,jquery 1.11.1

Frameworks I'm using: angular 1.5.8, jquery 1.11.1

推荐答案

您可以使用 String.indexOf String.includes

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

这篇关于如何在字符串中查找字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆