JavaScript String substr()
Exemplos
Extraia uma substring do texto:
let text = "Hello world!";
let result = text.substr(1, 4);"
Comece na posição 2:
let result = text.substr(2);
Mais exemplos abaixo.
Definição e uso
O substr()
método extrai uma parte de uma string.
O substr()
método começa em uma posição especificada e retorna um número especificado de caracteres.
O substr()
método não altera a string original.
Para extrair caracteres do final da string, use uma posição inicial negativa.
Sintaxe
string.substr(start, length)
Parâmetros
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 |
Valor de retorno
Modelo | Descrição |
Uma linha | Uma string contendo a parte extraída. Se length for 0 ou negativo, uma string vazia será retornada. |
Mais exemplos
Apenas o primeiro:
let result = text.substr(0, 1);
Apenas o último:
let result = text.substr(text.length-1, 1);
Os 6 últimos:
let result = text.substr(-5, 5);
Suporte ao navegador
substr()
é um recurso ECMAScript1 (ES1).
ES1 (JavaScript 1997) é totalmente suportado em todos os navegadores:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |