endsWith w JavaScript
Jak sprawdzić, czy łańcuch znaków kończy się określonym znakiem w JavaScript?
Przykład: mam ciąg
var str = "mystring#";
Chcę wiedzieć, czy ten ciąg kończy się na #
. Jak mogę to sprawdzić?
Czy istnieje metoda
endsWith()
w JavaScript?Jednym z rozwiązań, które mam, jest wzięcie długości łańcucha i pobranie ostatniego znaku i sprawdzenie go.
30 answers
Aktualizacja (Nov 24th, 2015):
Ta odpowiedź została pierwotnie opublikowana w roku 2010 (sześć lat temu.) więc proszę zwrócić uwagę na te wnikliwe komentarze:
- Shauna -
Aktualizacja dla Googlerów - wygląda na to, że ECMA6 dodaje tę funkcję. Artykuł MDN pokazuje również polyfill. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
Tworzenie podciągów nie jest drogie w nowoczesnych przeglądarkach; być może było to w 2010 roku, kiedy ta odpowiedź została opublikowana. W dzisiejszych czasach proste podejście
this.substr(-suffix.length) === suffix
jest najszybsze na Chrome, to samo na IE11 co indexOf, a tylko 4% wolniejsze (fergetaboutit) na Firefoksie: jsperf.com/endswith-stackoverflow/14 i szybciej, gdy wynik jest fałszywy: jsperf.com/endswith-stackoverflow-when-false oczywiście, z ES6 dodając endsWith, the kwestia sporna. :-)
ORYGINALNA ODPOWIEDŹ:
Wiem, że to pytanie sprzed roku... ale ja też tego potrzebuję i potrzebuję tego, aby działało między przeglądarkami... łączenie wszystkich odpowiedzi i komentarzy i nieco upraszczanie:String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
- nie tworzy podłańcucha
- używa natywnej funkcji
indexOf
dla najszybszych wyników - Pomiń niepotrzebne porównania używając drugiego parametru
indexOf
, Aby pominąć - Działa w Internecie Explorer
- brak komplikacji Regex
Ponadto, jeśli nie lubisz wypychać rzeczy w prototypach natywnej struktury danych, oto samodzielna wersja:
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
EDIT: jak zauważył @hamish w komentarzach, jeśli chcesz błądzić po bezpiecznej stronie i sprawdzić, czy implementacja została już dostarczona, możesz po prostu dodać typeof
w ten sposób:
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -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
2021-02-02 14:17:46
/#$/.test(str)
Będzie działać na wszystkich przeglądarkach, nie wymaga łatania małp String
i nie wymaga skanowania całego ciągu znaków, jak to robi lastIndexOf
, gdy nie ma dopasowania.
Jeśli chcesz dopasować stały ciąg znaków, który może zawierać specjalne znaki wyrażenia regularnego, takie jak '$'
, możesz użyć następującego wzoru:
function makeSuffixRegExp(suffix, caseInsensitive) {
return new RegExp(
String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
caseInsensitive ? "i" : "");
}
I wtedy możesz go użyć w ten sposób
makeSuffixRegExp("a[complicated]*suffix*").test(str)
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-19 17:09:48
-
Niestety nie.
if( "mystring#".substr(-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
2008-11-11 11:20:53
Dalej, to jest poprawna endsWith
implementacja:
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
}
Użycie lastIndexOf
po prostu tworzy niepotrzebne pętle procesora, jeśli nie ma dopasowania.
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-24 19:36:38
Ta wersja unika tworzenia podłańcucha i nie używa wyrażeń regularnych (niektóre odpowiedzi regex tutaj będą działać, inne są uszkodzone):
String.prototype.endsWith = function(str)
{
var lastIndex = this.lastIndexOf(str);
return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}
Jeśli wydajność jest dla ciebie ważna, warto sprawdzić, czy lastIndexOf
jest rzeczywiście szybsza niż tworzenie podłańcucha, czy nie. (Może to zależeć od używanego silnika JS...) Może być szybszy w przypadku dopasowania, a gdy ciąg jest mały - ale gdy ciąg jest ogromny, musi spojrzeć wstecz przez całość nawet choć nas to nie obchodzi: (
Do sprawdzania pojedynczego znaku, znalezienie długości, a następnie użycie {[2] } jest prawdopodobnie najlepszym sposobem.
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-19 12:44:28
Nie widziałem apporach z slice
metodą. Więc zostawiam to tutaj:
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
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-06-09 07:17:39
return this.lastIndexOf(str) + str.length == this.length;
Nie działa w przypadku, gdy oryginalna długość ciągu jest o jedną mniejszą od długości szukanego ciągu i szukany ciąg nie został znaleziony:
Lastindexof zwraca -1, następnie dodajesz długość szukanego ciągu i zostaje Ci oryginalna Długość łańcucha.
Możliwa poprawka to
return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
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-03-04 15:58:04
Od developer.mozilla.org String.prototyp.endsWith()
Podsumowanie
Metoda endsWith()
określa, czy łańcuch znaków kończy się znakami innego łańcucha, zwracając odpowiednio true lub false.
Składnia
str.endsWith(searchString [, position]);
Parametry
SearchString : Znaki, które mają być wyszukane na końcu tego ciągu.
Pozycja : Szukaj w tym łańcuchu tak, jakby ten łańcuch był tylko tym long; domyślnie rzeczywista długość tego łańcucha jest zaciśnięta w zakresie ustalonym przez długość tego łańcucha.
Opis
Ta metoda pozwala określić, czy łańcuch znaków kończy się innym łańcuchem.
Przykłady
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // true
alert( str.endsWith("to be") ); // false
alert( str.endsWith("to be", 19) ); // true
Dane techniczne
Specyfikacja języka ECMAScript 6th Edition (ECMA-262)
Zgodność przeglądarki
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-01-30 04:18:30
if( ("mystring#").substr(-1,1) == '#' )
-- lub --
if( ("mystring#").match(/#$/) )
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
2008-11-11 11:26:44
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}
Mam nadzieję, że to pomoże
var myStr = “ Earth is a beautiful planet ”;
var myStr2 = myStr.trim();
//==“Earth is a beautiful planet”;
if (myStr2.startsWith(“Earth”)) // returns TRUE
if (myStr2.endsWith(“planet”)) // returns TRUE
if (myStr.startsWith(“Earth”))
// returns FALSE due to the leading spaces…
if (myStr.endsWith(“planet”))
// returns FALSE due to trailing spaces…
Tradycyjny sposób
function strStartsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
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-17 11:05:10
Nie wiem jak ty, ale:
var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
Dlaczego wyrażenia regularne? Po co mieszać z prototypem? substr? chodź...
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
2013-05-02 08:01:18
Kolejna szybka alternatywa, która działała jak urok dla mnie, używając regex:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
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-14 18:15:40
Jeśli używasz lodash :
_.endsWith('abc', 'c'); // true
Jeśli nie korzystasz z lodash, możesz wypożyczyć go ze źródła .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-06-03 10:17:09
Właśnie dowiedziałem się o tej bibliotece ciągów:
Dołącz plik js, a następnie użyj zmiennej S
w następujący sposób:
S('hi there').endsWith('hi there')
Można go również użyć w NodeJS, instalując go:
npm install string
Następnie wymagając jej jako zmiennej S
:
var S = require('string');
Strona zawiera również linki do alternatywnych bibliotek ciągów, jeśli ta nie podoba ci się.
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-04-29 10:20:02
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return 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-05-19 08:21:44
Tak wiele rzeczy dla tak małego problemu, wystarczy użyć tego wyrażenia regularnego
var str = "mystring#";
var regex = /^.*#$/
if (regex.test(str)){
//if it has a trailing '#'
}
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-11-18 09:04:44
To było wiele lat na to pytanie. Dodam ważną aktualizację dla użytkowników, którzy chcą skorzystać z najczęściej głosowanych odpowiedzi.
Funkcje 'endsWith' są już dodane do JavaScript jako część ECMAScript 6 (experimental technology)
Poleć tutaj: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
Dlatego zaleca się dodanie sprawdzania istnienia natywnej implementacji, jak wspomniano w odpowiedź.
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-04-30 06:56:04
function check(str)
{
var lastIndex = str.lastIndexOf('/');
return (lastIndex != -1) && (lastIndex == (str.length - 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
2010-06-16 14:19:02
Sposobem na przyszłościowe zabezpieczenie i / lub zapobieganie nadpisywaniu istniejącego prototypu byłoby sprawdzenie, czy został on już dodany do prototypu Łańcuchowego. Oto moje podejście do nie-regex wysoko oceniona wersja.
if (typeof String.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -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-07-18 21:46:08
@ Chakrit ' s accepted answer is a solid way to do it yourself. Jeśli jednak szukasz spakowanego rozwiązania, polecam zajrzeć do podkreślenia .string , Jak zauważył @mlunoe. Używanie podkreślenia.string, kod będzie:
function endsWithHash(str) {
return _.str.endsWith(str, '#');
}
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-02-04 20:25:20
Po tych wszystkich długich odpowiedziach, znalazłem ten kawałek kodu prosty i łatwy do zrozumienia!
function end(str, target) {
return str.substr(-target.length) == target;
}
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-28 10:51:15
Jeśli nie chcesz używać lasIndexOf lub substr, to dlaczego nie spojrzeć na łańcuch w jego naturalnym stanie (np. tablica)
String.prototype.endsWith = function(suffix) {
if (this[this.length - 1] == suffix) return true;
return false;
}
Lub jako samodzielna Funkcja
function strEndsWith(str,suffix) {
if (str[str.length - 1] == suffix) return true;
return 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
2011-05-02 07:41:13
String.prototype.endWith = function (a) {
var isExp = a.constructor.name === "RegExp",
val = this;
if (isExp === false) {
a = escape(a);
val = escape(val);
} else
a = a.toString().replace(/(^\/)|(\/$)/g, "");
return eval("/" + a + "$/.test(val)");
}
// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));
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-06-22 15:06:02
Jest to implementacja endsWith :
String.prototype.endsWith = function (str) {
return this.length >= str.length && this.substr(this.length - str.length) == str;
}
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-06-20 04:43:07
Jest to implementacja endsWith
:
String.prototype.endsWith = function (str) {
return (this.length >= str.length) && (this.substr(this.length - str.length) === str);
}
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
2020-04-16 08:12:28
Opiera się to na zaakceptowanej odpowiedzi @ charkit, pozwalającej na przekazanie tablicy łańcuchów lub łańcuchów jako argumentu.
if (typeof String.prototype.endsWith === 'undefined') {
String.prototype.endsWith = function(suffix) {
if (typeof suffix === 'String') {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
}else if(suffix instanceof Array){
return _.find(suffix, function(value){
console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
return this.indexOf(value, this.length - value.length) !== -1;
}, this);
}
};
}
Wymaga to podkreślenia-ale prawdopodobnie można go dostosować, aby usunąć zależność podkreślenia.
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
2013-06-15 06:33:56
if(typeof String.prototype.endsWith !== "function") {
/**
* String.prototype.endsWith
* Check if given string locate at the end of current string
* @param {string} substring substring to locate in the current string.
* @param {number=} position end the endsWith check at that position
* @return {boolean}
*
* @edition ECMA-262 6th Edition, 15.5.4.23
*/
String.prototype.endsWith = function(substring, position) {
substring = String(substring);
var subLen = substring.length | 0;
if( !subLen )return true;//Empty string
var strLen = this.length;
if( position === void 0 )position = strLen;
else position = position | 0;
if( position < 1 )return false;
var fromIndex = (strLen < position ? strLen : position) - subLen;
return (fromIndex >= 0 || subLen === -fromIndex)
&& (
position === 0
// if position not at the and of the string, we can optimise search substring
// by checking first symbol of substring exists in search position in current string
|| this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
)
&& this.indexOf(substring, fromIndex) === fromIndex
;
};
}
Korzyści:
- Ta wersja nie jest tylko ponownym użyciem indexOf.
- Najlepszy występ na długich strunach. Oto Test prędkości http://jsperf.com/starts-ends-with/4
- W Pełni kompatybilny ze specyfikacją ecmascript. Przechodzi testy
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
2013-07-11 17:54:16
Nie używaj wyrażeń regularnych. Są powolne nawet w szybkich językach. Wystarczy napisać funkcję, która sprawdza koniec łańcucha znaków. Ta Biblioteka ma ładne przykłady: groundjs / util.js . Uważaj na dodawanie funkcji do ciągu znaków.prototyp. Ten kod ma ładne przykłady jak to zrobić: groundjs / prototype.js Ogólnie rzecz biorąc, jest to ładna biblioteka na poziomie językowym: groundjs Możesz również spojrzeć na lodash
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-01-05 02:03:46
Wszystkie z nich są bardzo przydatnymi przykładami. Dodanie String.prototype.endsWith = function(str)
pomoże nam po prostu wywołać metodę, aby sprawdzić, czy nasz łańcuch znaków kończy się na niej, czy nie, również regexp to zrobi.
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-05 14:58:29
Dla coffeescript
String::endsWith = (suffix) ->
-1 != @indexOf suffix, @length - suffix.length
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-23 09:40:10