Jak sprawdzić, czy łańcuch zawiera podłańcuch w JavaScript?
Zazwyczaj spodziewałbym się metody String.contains()
, ale nie wydaje się, aby była.
Jaki jest rozsądny sposób, aby to sprawdzić?
30 answers
Oto lista aktualnych możliwości:
1. (ES6) includes
-przejdź do odpowiedzi
var string = "foo",
substring = "oo";
string.includes(substring);
2. ES5 i starsze indexOf
var string = "foo",
substring = "oo";
string.indexOf(substring) !== -1;
String.prototype.indexOf
Zwraca pozycję łańcucha w drugim łańcuchu. Jeśli nie znaleziono, zwróci -1
.
3. search
-przejdź do odpowiedzi
var string = "foo",
expr = /oo/;
string.search(expr);
4. lodash obejmuje-przejdź do odpowiedzi
var string = "foo",
substring = "oo";
_.includes(string, substring);
5. RegExp-przejdź do odpowiedź
var string = "foo",
expr = /oo/; // no quotes here
expr.test(string);
6. Mecz-przejdź do odpowiedzi
var string = "foo",
expr = /oo/;
string.match(expr);
Testy wydajności pokazują, że indexOf
może być najlepszym wyborem, jeśli chodzi o punkt, w którym prędkość ma znaczenie.
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-03-28 12:31:10
Możesz łatwo dodać metodę contains
do String z tą instrukcją:
String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
Uwaga: Zobacz komentarze poniżej, aby uzyskać prawidłowy argument za niestosowaniem tego. Moja rada: używaj własnego osądu.
Alternatywnie:
if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; }
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-07-28 01:32:52
Problem z Twoim kodem polega na tym, że JavaScript uwzględnia wielkość liter. Twoja metoda wywołania
indexof()
Powinno być
indexOf()
Spróbuj to naprawić i zobacz, czy to pomoże:
if (test.indexOf("title") !=-1) {
alert(elm);
foundLinks++;
}
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
2012-10-18 19:24:03
Istnieje string.includes
w ES6:
"potato".includes("to");
> true
Uwaga Może być konieczne załadowanie es6-shim
lub podobnego, aby to działało na starszych przeglądarkach.
require('es6-shim')
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-04-13 15:57:05
var index = haystack.indexOf(needle);
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
2009-11-24 13:06:27
Możesz użyć metody JavaScript search()
.
Składnia to: string.search(regexp)
Zwraca pozycję meczu lub -1, jeśli nie znaleziono dopasowania.
Zobacz tam przykłady: jsref_search
Nie potrzebujesz skomplikowanej składni wyrażeń regularnych. Jeśli nie jesteś zaznajomiony z nimi proste st.search("title")
zrobi. Jeśli chcesz, aby twój test był niewrażliwy na wielkość liter, powinieneś wykonać st.search(/title/i)
.
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-05-22 18:25:39
String.prototype.includes()
został wprowadzony w ES6.
Określa, czy jeden łańcuch może być znaleziony w innym łańcuchu, zwracając odpowiednio wartość true lub false.
Składnia
var contained = str.includes(searchString [, position]);
Parametry
searchString
Ciąg znaków do wyszukania w tym łańcuchu.
position
Pozycja w tym łańcuchu, na której należy rozpocząć wyszukiwanie searchString
domyślnie wynosi 0.
Przykład
var str = "To be, or not to be, that is the question.";
console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("To be", 1)); // false
Uwaga
To może wymagać ES6 shim w starszych przeglądarkach.
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-08-25 06:40:47
Jeśli szukałeś alternatywy dla wypisania brzydkiego czeku -1, zamiast tego dodajesz ~ tilde.
if (~haystack.indexOf('needle')) alert('found');
Joe Zimmerman - zobaczysz, że użycie ~ on -1 konwertuje go na 0. Liczba 0 to a wartość False, co oznacza, że po przekonwertowaniu na Boolean. To może na początku nie wydawać się wielkim spostrzeżeniem, ale zapamiętaj funkcje takie jak indexOf zwrócą -1, gdy zapytanie nie jest znaleziono. Oznacza to, że zamiast pisać coś podobne do tego:
if (someStr.indexOf("a") >= 0) { // Found it } else { // Not Found }
Możesz teraz mieć mniej znaków w kodzie, więc możesz go napisać tak:
if (~someStr.indexOf("a")) { // Found it } else { // Not Found }
Więcej szczegóły tutaj
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-01-21 06:12:11
Ten fragment kodu powinien działać dobrze:
var str="This is testing for javascript search !!!";
if(str.search("for") != -1) {
//logic
}
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
2012-05-30 07:31:32
W języku JavaScript można zapisać metodę contains
:
if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}
Operator negacji bitowej (~
) służy do zamiany -1
na 0
(false), a wszystkie inne wartości będą niezerowe (True).
Operatory podwójnej negacji logicznej są używane do tworzenia liczby logicznej.
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-12-26 13:38:59
In ES5
var s = "foo";
alert(s.indexOf("oo") > -1);
W ES6 istnieją trzy nowe metody: includes()
, startsWith()
, endsWith()
.
var msg = "Hello world!";
console.log(msg.startsWith("Hello")); // true
console.log(msg.endsWith("!")); // true
console.log(msg.includes("o")); // true
console.log(msg.startsWith("o", 4)); // true
console.log(msg.endsWith("o", 8)); // true
console.log(msg.includes("o", 8)); // false
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-08-16 23:27:36
Zamiast używać fragmentów kodu znalezionych tu i ówdzie w sieci, możesz również użyć dobrze przetestowanej i udokumentowanej biblioteki. Dwie opcje polecam:
1. opcja: użyj Lodash: ma includes
"metoda": {]}
_.includes('foobar', 'ob');
// → true
Lodash jest najpopularniejszą zależnością biblioteki javascript dla npm i ma mnóstwo przydatnych metod javascript. Więc dla wielu projektów i tak byś tego chciał; -)
2. opcja: lub użyj podkreślenie.string : mA include
"metoda": {]}
_.str.include('foobar', 'ob');
// → true
Oto opis podkreślenia.string, dodaje po prostu 9kb, ale daje wszystkie zalety dobrze przetestowanej i udokumentowanej biblioteki nad fragmentami kodu copy ' n ' Paste:
Podkreślenie.string jest biblioteką JavaScript dla wygodnej manipulacji z ciągami, rozszerzenie dla podkreślenia.js zainspirowany prototypem.js, Racja.js, podkreślenie i piękny język Ruby.
Podkreślenie.string zapewnia kilka przydatnych funkcji: capitalize, clean, includes, count, escapeHTML, unescapeHTML, insert, splice, startsWith, endsWith, titleize, trim, truncate i tak dalej.
Uwaga, podkreślam.ciąg jest pod wpływem podkreślenia.js ale może być używany bez niego.
Wreszcie: z wersją JavaScript ES6 jest wbudowany includes
"metoda": {]}
'foobar'.includes('ob');
// → true
Większość nowoczesnych przeglądarek już go obsługuje, miej oko na Tabela kompatybilności ES6 .
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-03-03 22:09:28
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-01-04 04:38:49
Użyj wyrażenia regularnego:
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
2014-07-21 18:38:48
Inną opcją jest:
Możesz użyć funkcji match, czyli czegoś takiego jak:
x = "teststring";
if (x.match("test")) {
// Code
}
Match () może również pracować z wyrażeniem regularnym:
x = "teststring";
if (x.match(/test/i)) {
// Code
}
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-01-26 08:50:20
Szukałeś .indexOf
MDN.
indexOf
zwróci indeks do dopasowanego podłańcucha. Indeks będzie skorelowany z miejscem, w którym zaczyna się podłańcuch. Jeśli nie ma dopasowania, zwracane jest -1. Oto simple demo tego pojęcia:
var str = "Hello World"; // For example, lets search this string,
var term = "World"; // for the term "World",
var index = str.indexOf(term); // and get its index.
if (index != -1) { // If the index is not -1 then the term was matched in the string,
alert(index); // and we can do some work based on that logic. (6 is alerted)
}
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-04-27 11:43:43
Musisz wywołać indexOf przez wielkie "O", jak wspomniano. Należy również zauważyć, że w JavaScript klasa jest słowem zastrzeżonym, trzeba użyć className aby uzyskać ten atrybut danych. Prawdopodobnie zawodzi, ponieważ zwraca wartość null. Możesz wykonać następujące czynności, aby uzyskać wartość swojej klasy...
var test = elm.getAttribute("className");
//or
var test = elm.className
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
2009-11-24 15:52:20
To mi po prostu zadziałało. Wybiera dla łańcuchów, które nie zawierają wyrażenia "Deleted:"
if (eventString.indexOf("Deleted:") == -1)
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-11-20 01:35:31
Ponieważ pytanie jest dość popularne, pomyślałem, że mogę dodać trochę nowoczesnego smaku do kodu.
// const : creates an immutable constant
const allLinks = document.getElementsByTagName("a");
// [].reduce.call : gives access to the reduce method on a HTMLCollection
// () => {} : ES6 arrow function
const foundLinks = [].reduce.call(allLinks, (sum, link) => {
// bitwise OR : converts the boolean value to a number
return sum + (link.classList.contains("title") | 0);
}, 0);
// template literal
console.log(`Found ${foundLinks || "no"} title class`);
BTW, poprawna odpowiedź to błędne zapisanie indexOf
lub niestandardowe String.contains
.
Wczytywanie zewnętrznej biblioteki (szczególnie jeśli kod jest napisany w czystym JavaScript) lub mieszanie z String.prototype
lub używanie wyrażenia regularnego jest trochę przesadą.
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-19 14:32:05
Istnieje elegancki i lepszy sposób, aby to zrobić i jest to za pomocą operatora (bitowo nie).
if(~"John".indexOf("J")) {
alert("Found")
}
else {
alert("Not Found");
}
Bitowe Not konwertuje " x " Na - (x + 1), więc jeśli x okaże się -1 z metody indexOf.następnie zostanie on zamieniony na - (-1 + 1) = -0, co jest wartością falsy .
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
2014-12-07 11:05:58
String.prototype.indexOf()
czy String.prototype.search()
?!
Jak już wspomnieli inni, łańcuchy JavaScript mają zarówno indexOf
oraz search
metoda.
Zasadnicza różnica między obydwoma wersjami jest taka, że indexOf
dotyczy tylko zwykłych podłańcuchów, podczas gdy search
obsługuje również wyrażenia regularne. Oczywiście zaletą używania indexOf
jest to, że jest szybszy.
Realizacja Twojego metoda własna String.prototype.contains()
Jeśli chcesz dodać własną metodę contains
do każdego ciągu, najlepszym sposobem na to będzie podejście @zzzzBov:
if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}
Użyłbyś go tak:
'Hello World'.contains('orl');
Implementacja niestandardowej biblioteki narzędzi
Jest ogólnie źle widziane dodawanie własnych metod do standardowych obiektów w JavaScript, na przykład, ponieważ może to zakłócić kompatybilność.
Jeśli naprawdę chcesz własną metodę contains
i / lub inne niestandardowe metody łańcuchowe, lepiej utworzyć własną bibliotekę narzędzi i dodać własne metody łańcuchowe do tej biblioteki:
var helper = {};
helper.string = {
contains : function (haystack, needle) {
return !!~haystack.indexOf(needle);
},
...
};
Użyłbyś go tak:
helper.string.contains('Hello World', 'orl');
Korzystanie z biblioteki narzędzi innych firm
Jeśli nie chcesz tworzyć własnej biblioteki pomocniczej, zawsze istnieje - oczywiście - opcja użycia biblioteki narzędzi innej firmy. Jak wspomina @Nachtigall, najpopularniejsze to Lodash i podkreślenie.js .
W Lodash możesz użyć _.includes()
, którego używasz tak:
_.includes('Hello World', 'orl');
W Podkreśleniu.js, możesz użyć _.str.include()
, którego używasz w ten sposób:
_.str.include('Hello World', 'orl');
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-05-23 10:31:37
Przykład
var a = "Test String";
if(a.search("ring")!=-1){
//exist
} else {
//not found
}
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-05-31 06:06:34
Proste obejście
if (!String.prototype.contains) {
String.prototype.contains= function() {
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
Możesz użyć w następujący sposób
"hello".contains("he") // true
"hello world".contains("lo w")//true
"hello world".contains("lo wa")//false
"hello world".contains(" ")//true
"hello world".contains(" ")//false
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-08-21 09:45:55
ES6 zawiera String.prototype.includes
.
Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
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-06-02 19:19:38
Kod JavaScript do użycia metody contains
w tablicy:
<html>
<head>
<h2>Use of contains() method</h2>
<script>
Array.prototype.contains = function (element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) {
return true;
}
}
return false;
}
arr1 = ["Rose", "India", "Technologies"];
document.write("The condition is "+arr1.contains("India")+"<br>");
</script>
</head>
<b>[If the specified element is present in the array, it returns true otherwise
returns false.]</b>
</html>
W podanym kodzie metoda contains
określa czy dany element jest obecny w tablicy czy nie. Jeśli podany element jest obecny w tablicy, zwraca true, w przeciwnym razie zwraca false.
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
2014-10-26 10:21:27
Aby zebrać jakieś poprawne rozwiązania:
var stringVariable = "some text";
var findString = "text";
//using `indexOf()`
var containResult1 = stringVariable.indexOf(findString) != -1;
document.write(containResult1+', ');
//using `lastIndexOf()`
var containResult2 = stringVariable.lastIndexOf(findString) != -1;
document.write(containResult2+', ');
//using `search()`
var containResult3 = stringVariable.search(findString) != -1;
document.write(containResult3+', ');
//using `split()`
var containResult4 = stringVariable.split(findString)[0] != stringVariable;
document.write(containResult4+'');
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-18 04:43:38
Ponieważ istnieje Skarga na używanie prototypu, i ponieważ użycie {[1] } sprawia, że kod jest mniej czytelny, a ponieważ wyrażenie regularne jest overkill:
function stringContains(inputString, stringToFind) {
return (inputString.indexOf(stringToFind) != -1);
}
To jest kompromis, na który się zdecydowałem.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
2014-03-25 12:22:31
JavaScript
var str = "My big string contain apples and oranges";
var n = str.indexOf("apples");
alert(n); //will alert 22, -1 if not found
JQuery
<p>My big string contain apples and oranges</p>
alert($("p:contains(apples)")[0] != undefined); //will alert true if found
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
2014-12-16 18:44:26
Użyj wbudowanego i najprostszego, tj. match()
na łańcuchu. Aby osiągnąć to, czego oczekujesz, zrób to:
var stringData ="anyString Data";
var subStringToSearch = "any";
// This will give back the substring if matches and if not returns null
var doesContains = stringData.match(subStringToSearch);
if(doesContains !=null) {
alert("Contains Substring");
}
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
2014-05-02 20:26:01
Najprostszym sposobem jest użycie indexOf . Aby sprawdzić łańcuch string
dla fragmentu substr
możesz użyć tej metody:
string = "asdf";
substr = "as";
alert(string.indexOf(substr) == -1 ? false : true);
Jak chciałeś funkcję string.contains()
, możesz zaimplementować ją samodzielnie w następujący sposób:
String.prototype.contains = function(test) {
return this.indexOf(test) == -1 ? false : true;
};
Teraz możesz użyć tej metody ecen shorter, aby sprawdzić, czy łańcuch zawiera specjalny podłańcuch:
string = "asdf";
alert(string.contains("as"));
OtoJSFiddle .
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
2014-10-26 10:30:27