JavaScript řetězec substr()
Příklady
Extrahujte z textu podřetězec:
let text = "Hello world!";
let result = text.substr(1, 4);"
Začněte na pozici 2:
let result = text.substr(2);
Další příklady níže.
Definice a použití
Metoda substr()
extrahuje část řetězce.
Metoda substr()
začíná na zadané pozici a vrací zadaný počet znaků.
Metoda substr()
nemění původní řetězec.
Chcete-li extrahovat znaky z konce řetězce, použijte zápornou počáteční pozici.
Syntax
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 |
Návratová hodnota
Typ | Popis |
Řetězec | Řetězec obsahující extrahovanou část. Pokud je délka 0 nebo záporná, vrátí se prázdný řetězec. |
Další příklady
Pouze první:
let result = text.substr(0, 1);
Pouze poslední:
let result = text.substr(text.length-1, 1);
Posledních 6:
let result = text.substr(-5, 5);
Podpora prohlížeče
substr()
je funkce ECMAScript1 (ES1).
ES1 (JavaScript 1997) je plně podporován ve všech prohlížečích:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |