PT
JavaScript - remover os 3 Ășltimos caracteres da string
3 points
Neste artigo, nĂłs veremos como remover os trĂȘs Ășltimos caracteres da string em JavaScript.
Essa abordagem permite obter substring usando Ăndices negativos. EntĂŁo, usando Ăndices 0
e -3
como intervalo, obtemos <0, text.length - 3>
intervalo de texto.
xxxxxxxxxx
1
var text = 'abcde';
2
var substring = text.slice(0, -3);
3
â
4
console.log(substring); // ab
Essa é uma abordagem alternativa para solução baseada no método slice.
xxxxxxxxxx
1
var text = 'abcde';
2
var substring = text.substring(0, text.length - 3);
3
â
4
console.log(substring); // ab
Hå outro truque que permite substituir todos os caracteres que correspondem à condição de expressão. Utilizando .{0,3}$
padrão, combinamos todos os 3 caracteres (até 3 caracteres) localizados no final da string.
xxxxxxxxxx
1
var text = 'abcde';
2
var substring = text.replace(/.{0,3}$/, '');
3
â
4
console.log(substring); // ab