Esta página foi traduzida do inglês pela comunidade.Saiba mais e junte-se à comunidade MDN Web Docs.
String.prototype.substr()
O métodosubstr() retorna uma parte da string, começando no índice especificado e estendendo-se por um determinado número de caracteres posteriormente.
In this article
Experimente
const str = "Mozilla";console.log(str.substr(1, 2));// Expected output: "oz"console.log(str.substr(2));// Expected output: "zilla"Sintaxe
str.substr(start[, length])
Parâmetros
Valor de retorno
Uma nova string contendo a seção extraída da string fornecida.
Descrição
Osubstr() extrai caracteres de comprimento de umastr, contando a partir do índice inicial.
- Se o
startfor um número positivo, o índice começa a contar no início da string. Seu valor é limitado ao tamanho da string (str.length). - Se o
startfor um número negativo, o índice começa a contar a partir do final da string. Seu valor é limitado ao tamanho da string (-str.length).
Nota:No Microsoft JScript, valores negativos no argumentostart não são considerados como referência ao final da string.
Exemplos
>Usandosubstr()
js
var aString = "Mozilla";console.log(aString.substr(0, 1)); // 'M'console.log(aString.substr(1, 0)); // ''console.log(aString.substr(-1, 1)); // 'a'console.log(aString.substr(1, -1)); // ''console.log(aString.substr(-3)); // 'lla'console.log(aString.substr(1)); // 'ozilla'console.log(aString.substr(-20, 2)); // 'Mo'console.log(aString.substr(20, 2)); // ''Polyfill
JScript da Microsoft não suporta valores negativos para o índice destart. Se você deseja usar esse recurso, você pode usar o seguinte código de compatibilidade para evitar esse erro:
js
// only run when the substr() function is brokenif ("ab".substr(-1) != "b") { /** * Get the substring of a string * @param {integer} start where to start the substring * @param {integer} length how many characters to return * @return {string} */ String.prototype.substr = (function (substr) { return function (start, length) { // call the original method return substr.call( this, // did we get a negative start, calculate how much it is from the beginning of the string // adjust the start parameter for negative value start < 0 ? this.length + start : start, length, ); }; })(String.prototype.substr);}Especificações
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-string.prototype.substr> |