| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/substring | [Back] [Original] |
Get to know MDN better
Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade MDN Web Docs.
This feature is well established and works across many devices and browser versions. Its been available across browsers since julho de 2015.
O mtodo substring() retorna a parte da string entre os ndices inicial e final, ou at o final da string.
str.substring(indexStart[, indexEnd])
indexStartUm inteiro entre 0 e o comprimento da string (str.length), especificando a posio na string do primeiro caractere a ser includo na substring retornada.
indexEndOpcional. Um inteiro entre 0 e o comprimento da string (str.length), especificando a posio na string do primeiro caractere a no ser mais includo na substring retornada.
Uma nova string contendo a parte especificada da string fornecida.
substring() extrai caracteres desde indexStart at, mas no incluindo, indexEnd. Em particular:
indexStart igual a indexEnd, substring() retorna uma string vazia.indexEnd for omitido, substring() extrai caracteres at o fim da string.0 ou NaN, ele ser tratado como 0.stringName.length, ele ser tratado como se fosse stringName.lengthSe indexStart for maior que indexEnd, ento o efeito do substring() como se os dois argumentos estivessem trocados, por exemplo, str.substring(1, 0) == str.substring(0, 1).
substring()O seguinte exemplo usa substring() para mostrar caracteres da palavra 'Mozilla':
var anyString = "Mozilla";
// Mostra "Moz"
console.log(anyString.substring(0, 3));
console.log(anyString.substring(3, 0));
// Mostra "lla"
console.log(anyString.substring(4, 7));
console.log(anyString.substring(7, 4));
// Mostra "Mozill"
console.log(anyString.substring(0, 6));
// Mostra "Mozilla"
console.log(anyString.substring(0, 7));
console.log(anyString.substring(0, 10));
substring() com lengthO exemplo a seguir usa o mtodo substring() e a propriedade length para extrair os ltimos caracteres de uma string especfica. Este mtodo pode ser mais fcil de lembrar, visto que voc no precisa saber os ndices inicial e final como faria nos exemplos acima.
// Mostra 'illa', os ltimos 4 caracteres
let anyString = "Mozilla";
let anyString4 = anyString.substring(anyString.length - 4);
console.log(anyString4);
// Mostra 'zilla', os ltimos 5 caracteres
let anyString = "Mozilla";
let anyString5 = anyString.substring(anyString.length - 5);
console.log(anyString5);
substring() e substr()H uma diferena sutil entre os mtodos substring() e substr(), ento voc deve ter cuidado para no confundi-los.
Os argumentos de substring() representam os ndices inicial e final, enquanto os argumentos de substr() representam o ndice inicial e o nmero de caracteres a serem includos na string retornada.
Alm disso, substr() considerado um recurso legacy no ECMAScript e pode ser removido em verses futuras, portanto, melhor evitar us-lo, se possvel.
let text = "Mozilla";
console.log(text.substring(2, 5)); // retorna "zil"
console.log(text.substr(2, 3)); // retorna "zil"
substring() e slice()Os mtodos substring() e slice() so quase idnticos, mas existem algumas diferenas sutis entre os dois, especialmente na forma como os argumentos negativos so tratados.
O mtodo substring() troca seus dois argumentos se indexStart for maior que indexEnd, o que significa que uma string ainda ser retornada. O mtodo slice() retorna uma string vazia caso o mesmo ocorra.
let text = "Mozilla";
console.log(text.substring(5, 2)); // retorna "zil"
console.log(text.slice(5, 2)); // retorna ""
Se um ou ambos os argumentos forem negativos ou NaN, o mtodo substring() os tratar como se fossem 0.
console.log(text.substring(-5, 2)); // retorna "Mo"
console.log(text.substring(-5, -2)); // retorna ""
slice() tambm trata os argumentos NaN como 0, mas quando recebe valores negativos, ele conta regressivamente a partir do final da string para encontrar os ndices.
console.log(text.slice(-5, 2)); // retorna ""
console.log(text.slice(-5, -2)); // retorna "zil"
Veja a pgina slice() para mais exemplos com nmeros negativos.
substring() com uma stringO seguinte exemplo substitui uma substring dentro de uma string. Ela ir substituir ambos caracteres e substrings individualmente. A funo invocada na linha final do exemplo altera a string "Brave New World" para "Brave New Web".
function replaceString(oldS, newS, fullS) {
// Substitui oldS por newS na string fullS
for (var i = 0; i < fullS.length; i++) {
if (fullS.substring(i, i + oldS.length) == oldS) {
fullS =
fullS.substring(0, i) +
newS +
fullS.substring(i + oldS.length, fullS.length);
}
}
return fullS;
}
replaceString("World", "Web", "Brave New World");
Note que isto pode resultar em um loop infinito se oldS for um substring de newS por exemplo, se voc tentou substituir "World" com "OtherWorld". O melhor mtodo para substituir strings o seguinte:
function replaceString(oldS, newS, fullS) {
return fullS.split(oldS).join(newS);
}
O cdigo acima serve como um exemplo para operaes com substring. Se voc precisa substituir substrings, na maioria das vezes voc vai querer usar String.prototype.replace().
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-string.prototype.substring |
This page was last modified on 3 de fev. de 2024 by MDN contributors.
StringString.prototype.anchor()at()String.prototype.big()String.prototype.blink()String.prototype.bold()String.prototype.charAt()String.prototype.charCodeAt()String.prototype.codePointAt()String.prototype.concat()String.prototype.endsWith()String.prototype.fixed()String.prototype.fontcolor()String.prototype.fontsize()String.prototype.includes()String.prototype.indexOf()isWellFormed()String.prototype.italics()String.prototype.lastIndexOf()String.prototype.link()String.prototype.localeCompare()String.prototype.match()String.prototype.matchAll()String.prototype.normalize()String.prototype.padEnd()String.prototype.padStart()String.prototype.repeat()String.prototype.replace()String.prototype.replaceAll()String.prototype.search()String.prototype.slice()String.prototype.small()String.prototype.split()String.prototype.startsWith()String.prototype.strike()String.prototype.sub()String.prototype.substr()String.prototype.substring()String.prototype.sup()String.prototype.toLocaleLowerCase()String.prototype.toLocaleUpperCase()String.prototype.toLowerCase()String.prototype.toString()String.prototype.toUpperCase()toWellFormed()String.prototype.trim()String.prototype.trimEnd()String.prototype.trimStart()String.prototype.valueOf()String.prototype[@@iterator]()Object/FunctionObject.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |