如何在JavaScript中检查字符串是否包含来自子字符串数组的文本?

318

很简单。在JavaScript中,我需要检查一个字符串是否包含数组中包含的任何子字符串。


在新的HTML5-JavaScript版本中,难道没有map()函数吗?我记得曾经读过相关的内容... - Martin Hennings
@Martin:说得好,不是“map”,而是“some”。使用“some”会有所帮助,但你需要传递一个函数。 - T.J. Crowder
24个回答

3

虽然有点晚了,但我刚刚遇到了这个问题。在我的项目中,我使用以下代码来检查一个字符串是否在数组中:

["a","b"].includes('a')     // true
["a","b"].includes('b')     // true
["a","b"].includes('c')     // false

通过这种方式,您可以使用预定义的数组检查它是否包含一个字符串:

var parameters = ['a','b']
parameters.includes('a')    // true

这是最干净的答案。非常感谢! - Abid Khairy
这里的问题不是一个数组中的字符串,而是在一个句子中的字符串数组。 - Justin Farrugia

3

使用搜索字符串或搜索字符串数组来搜索标签或关键字数组的Javascript函数。(使用ES5的some数组方法和ES6的箭头函数)

// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
    // array matches
    if (Array.isArray(b)) {
        return b.some(x => a.indexOf(x) > -1);
    }
    // string match
    return a.indexOf(b) > -1;
}

使用示例:

var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
    // 1 or more matches found
}

3
如果数组不是很大,您可以使用indexOf()函数循环检查每个子字符串与该字符串进行比较。或者,您也可以构建一个正则表达式,其中包含每个子字符串作为可选项,这可能更有效率。

1
假设我们有一个由100个子字符串组成的列表。哪种方法更有效:正则表达式或循环? - Diyorbek Sadullaev

3

最佳答案在这里:这也是不区分大小写的。

    var specsFilter = [.....];
    var yourString = "......";

    //if found a match
    if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
        // do something
    }

2
从T.J. Crowder的解决方案中借鉴,我创建了一个原型来解决这个问题:
Array.prototype.check = function (s) {
  return this.some((v) => {
    return s.indexOf(v) >= 0;
  });
};

2

在T.J Crowder的回答基础上进行改进

使用转义的正则表达式来测试至少出现一次的子字符串中的至少一个。

function buildSearch(substrings) {
  return new RegExp(
    substrings
    .map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
    .join('{1,}|') + '{1,}'
  );
}


var pattern = buildSearch(['hello','world']);

console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));


2

我并不建议您去扩展/修改String的原型,但这是我所做的:

String.prototype.includes()

String.prototype.includes = function (includes) {
    console.warn("String.prototype.includes() has been modified.");
    return function (searchString, position) {
        if (searchString instanceof Array) {
            for (var i = 0; i < searchString.length; i++) {
                if (includes.call(this, searchString[i], position)) {
                    return true;
                }
            }
            return false;
        } else {
            return includes.call(this, searchString, position);
        }
    }
}(String.prototype.includes);

console.log('"Hello, World!".includes("foo");',          "Hello, World!".includes("foo")           ); // false
console.log('"Hello, World!".includes(",");',            "Hello, World!".includes(",")             ); // true
console.log('"Hello, World!".includes(["foo", ","])',    "Hello, World!".includes(["foo", ","])    ); // true
console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false


1
使用underscore.js或lodash.js,您可以在字符串数组上执行以下操作:
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];

var filters = ['Bill', 'Sarah'];

contacts = _.filter(contacts, function(contact) {
    return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});

// ['John']

而且在一个字符串上:

var contact = 'Billy';
var filters = ['Bill', 'Sarah'];

_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });

// true

1
我曾经遇到过这样的问题。我有一个URL,想要检查链接是否以图像格式或其他文件格式结尾,具有图像格式数组。这是我所做的事情:
const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
    
// false

1
如果你正在处理一个由完整的“单词”组成的子字符串长列表,这些单词由空格或任何其他常见字符分隔,你可以在搜索时变得聪明一些。
首先将字符串分成X、X+1、X+2等多个组,直到Y。X和Y应该是你的子字符串中最少和最多单词的数量。例如,如果X为1,Y为4,“Alpha Beta Gamma Delta”变成了:
"Alpha" "Beta" "Gamma" "Delta"
"Alpha Beta" "Beta Gamma" "Gamma Delta"
"Alpha Beta Gamma" "Beta Gamma Delta"
"Alpha Beta Gamma Delta"
如果X为2,Y为3,则省略第一行和最后一行。
现在,如果你将此列表插入到Set(或Map)中,就可以快速地进行搜索,比通过字符串比较要快得多。
缺点是你无法搜索像“ta Gamm”这样的子字符串。当然,你可以通过按字符而不是按单词拆分来允许这种情况,但这样做通常需要构建一个巨大的Set,花费的时间/内存超过了好处。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接