JavaScript String substr()
Przykłady
Wyodrębnij podciąg z tekstu:
let text = "Hello world!";
let result = text.substr(1, 4);"
Zacznij od pozycji 2:
let result = text.substr(2);
Więcej przykładów poniżej.
Definicja i użycie
Metoda substr()
wyodrębnia część ciągu.
Metoda substr()
zaczyna się od określonej pozycji i zwraca określoną liczbę znaków.
Metoda substr()
nie zmienia oryginalnego ciągu.
Aby wyodrębnić znaki z końca ciągu, użyj ujemnej pozycji początkowej.
Składnia
string.substr(start, length)
Parametry
Parameter | Description |
start | Required. The start position. First character is at index 0. If start is greater than the length, substr() returns "". If start is negative, substr() counts from the end of the string. |
length | Optional. The number of characters to extract. If omitted, it extracts the rest of the string |
Wartość zwrotu
Rodzaj | Opis |
sznurek | Ciąg zawierający wyodrębnioną część. Jeśli długość wynosi 0 lub jest ujemna, zwracany jest pusty ciąg. |
Więcej przykładów
Tylko pierwszy:
let result = text.substr(0, 1);
Tylko ostatnie:
let result = text.substr(text.length-1, 1);
Ostatnie 6:
let result = text.substr(-5, 5);
Obsługa przeglądarki
substr()
to funkcja ECMAScript1 (ES1).
ES1 (JavaScript 1997) jest w pełni obsługiwany we wszystkich przeglądarkach:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |