Jak sprawdzić, czy łańcuch zawiera tekst z tablicy podłańcuchów w JavaScript?

Całkiem prosto. W javascript, muszę sprawdzić, czy łańcuch zawiera jakieś podłańcuchy trzymane w tablicy.

Author: slick, 2011-04-07

13 answers

Nie ma nic wbudowanego, które zrobi to za ciebie, będziesz musiał napisać dla niego funkcję.

Jeśli znasz łańcuchy znaków nie zawierają żadnych znaków specjalnych w wyrażeniach regularnych, możesz trochę oszukać, jak to:

if (new RegExp(substrings.join("|")).test(string)) {
    // At least one match
}

...który tworzy Wyrażenie regularne, które jest ciągiem alternacji dla podciągów, których szukasz (np. one|two) i sprawdza, czy są pasujące do któregokolwiek z nich, ale czy któryś z podciągów zawiera znaki specjalne w wyrażeniach regularnych (*, [, itd.), najpierw musiałbyś od nich uciec, a zamiast tego lepiej zrobić nudną pętlę.

Darmowy przykład na żywo


Update :

W komentarzu do pytania, Martin pyta o nową funkcję Array#map W ECMAScript5. map nie jest aż tak pomocna, ale some jest:

if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
    // There's at least one
}

Przykład na żywo (działa tylko na nowoczesnych przeglądarkach)

Umysł ty, to oznacza trochę narzutu, i masz to tylko na implementacjach zgodnych z ECMAScript5 (więc, nie IE7 lub wcześniej, na przykład; może nawet nie IE8), ale nadal, jeśli jesteś naprawdę w tym stylu programowania... (I możesz użyć ecmascript5 shim, ten lub którykolwiek z kilku innych.)

 125
Author: T.J. Crowder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-25 07:25:29
var yourstring = 'tasty food'; // the string to check against


var substrings = ['foo','bar'],
    length = substrings.length;
while(length--) {
   if (yourstring.indexOf(substrings[length])!=-1) {
       // one of the substrings is in yourstring
   }
}
 43
Author: raveren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-04 09:12:58
function containsAny(str, substrings) {
    for (var i = 0; i != substrings.length; i++) {
       var substring = substrings[i];
       if (str.indexOf(substring) != - 1) {
         return substring;
       }
    }
    return null; 
}

var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);
 16
Author: Jim Blackler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-05 08:33:58

Dla ludzi Googlujących,

Solidna odpowiedź powinna być.

const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
   // Will only return when the `str` is included in the `substrings`
}
 11
Author: halfcube,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-30 08:47:36

One line solution

substringsArray.some(substring=>yourBigString.includes(substring))

Zwraca true\false if substring exists\does'nt exist

Potrzebuje wsparcia ES6

 7
Author: Praveena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-21 06:53:16
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}

Edytuj: Jeśli kolejność testów nie ma znaczenia, możesz użyć tego (tylko z jedną zmienną pętli):

var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}
 6
Author: user,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-20 12:43:51

Jeśli tablica nie jest duża, możesz po prostu zapętlić i sprawdzić łańcuch znaków z każdym podłańcuchem indywidualnie za pomocą indexOf(). Alternatywnie można skonstruować Wyrażenie regularne z podciągami jako alternatywy, które mogą być bardziej efektywne lub nie.

 2
Author: Gintautas Miliauskas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-07 14:22:42

Funkcja Javascript do wyszukiwania tablicy tagów lub słów kluczowych za pomocą ciągu wyszukiwania lub tablicy ciągów wyszukiwania. (Używa ES5 niektóre metody array i ES6 funkcje strzałek )

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

Przykładowe użycie:

var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
    // 1 or more matches found
}
 2
Author: David Douglas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-27 23:09:07

Używanie podkreślnika.js lub lodash.js, możesz wykonać następujące czynności na tablicy łańcuchów:

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']

I na pojedynczym łańcuchu:

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

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

// true
 0
Author: BuffMcBigHuge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-08 00:39:27

Nie żebym sugerował, żebyś rozszerzył / zmodyfikował prototyp String, Ale To właśnie zrobiłem:

Sznurek.prototyp.zawiera()

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
 0
Author: akinuri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-20 07:36:03

Jest bardzo późno, ale właśnie wpadłem na ten problem. W moim własnym projekcie użyłem poniższego, aby sprawdzić, czy łańcuch jest w tablicy:

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

W ten sposób można pobrać predefiniowaną tablicę i sprawdzić, czy zawiera ona ciąg znaków:

var parameters = ['a','b']
parameters.includes('a')    // true
 0
Author: Nick Huff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-20 17:15:35

Bazując na odpowiedzi T. J Crowdera

Użycie regexp w celu sprawdzenia wystąpienia "co najmniej raz", co najmniej jednego z podłańcuchów.

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 ...'));
 0
Author: DhavalW,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-27 15:47:02

Na podstawie rozwiązania T. J. Crowdera stworzyłem prototyp, aby poradzić sobie z tym problemem:

Array.prototype.check = function (s) {
  return this.some((v) => {
    return s.indexOf(v) >= 0;
  });
};
 0
Author: alavry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-18 23:10:31