JavaScript substr(): migrar a slice() o substring()
text.substr(start, length) obtiene una subcadena de la longitud indicada a partir del inicio. Es una función heredada por compatibilidad web. slice() y substring() usan un índice final como segundo argumento.
Leer el segundo argumento como longitud
Los índices empiezan en cero. En '123456789', substr(1, 5) devuelve '23456'. Sin longitud, devuelve el resto. La entrada conserva su valor. Consulta String.prototype.substr().
const text = '123456789';
console.log(text.substr(1, 5)); // '23456'
console.log(text.substr(0, 5)); // '12345'
console.log(text.substr(3)); // '456789'
console.log(text); // '123456789'
Tratar inicios negativos y límites
Un inicio negativo se cuenta desde el final y uno demasiado pequeño se ajusta a cero. Una longitud de cero o menos, o un inicio a partir del final, devuelve una cadena vacía. Se cuentan unidades de código UTF-16 (formato de transformación Unicode de 16 bits), que pueden dividir un emoji.
console.log('123456789'.substr(-2, 2)); // '89'
console.log('123456789'.substr(2, 0)); // ''
console.log('123456789'.substr(2, -1)); // ''
console.log('123456789'.substr(99, 2)); // ''
Probar un ejemplo completo de comparación
Guarda el archivo UTF-8 como substr-example.html y ábrelo. Ambos métodos dan '23456' al principio. Sin longitud se obtiene el resto. Con inicio negativo solo verás el resultado antiguo y un aviso, porque la fórmula simple se usa para enteros no negativos.
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Comparar substr y slice</title>
</head>
<body>
<label for="source">Cadena original</label>
<input id="source" type="text" value="123456789">
<label for="start">Índice inicial</label>
<input id="start" type="number" step="1" value="1">
<label for="length">Longitud (vacía para llegar al final)</label>
<input id="length" type="number" step="1" value="5">
<button id="run" type="button">Comparar</button>
<button id="reset" type="button">Restablecer</button>
<pre id="output" aria-live="polite"></pre>
<script>
const source = document.querySelector('#source');
const start = document.querySelector('#start');
const length = document.querySelector('#length');
const output = document.querySelector('#output');
function show() {
const s = Number(start.value);
const lengthText = length.value.trim();
const count = lengthText === '' ? undefined : Number(lengthText);
if (start.validity.badInput || length.validity.badInput ||
!Number.isSafeInteger(s) || (count !== undefined && !Number.isSafeInteger(count))) {
output.textContent = 'Introduce enteros seguros para inicio y longitud. La longitud puede quedar vacía.';
return;
}
const oldResult = count === undefined
? source.value.substr(s)
: source.value.substr(s, count);
let alternative = 'Revisa el intervalo antes de migrar argumentos negativos.';
if (s >= 0 && (count === undefined || count >= 0)) {
const newResult = count === undefined
? source.value.slice(s)
: source.value.slice(s, s + count);
alternative = `Resultado de slice(): ${JSON.stringify(newResult)}`;
}
output.textContent = `Resultado de substr(): ${JSON.stringify(oldResult)}\n${alternative}`;
}
document.querySelector('#run').addEventListener('click', show);
document.querySelector('#reset').addEventListener('click', () => {
source.value = '123456789';
start.value = '1';
length.value = '5';
show();
});
show();
</script>
</body>
</html>
Migrar a slice() o substring()
Con inicio y longitud enteros no negativos, slice(start, start + length) reproduce el resultado. Con otros valores puede variar. slice() cuenta índices finales negativos desde el final. substring() convierte negativos en cero e intercambia los extremos invertidos. Consulta String.prototype.substring().
const text = '01234';
console.log(text.substr(1, -2)); // ''
console.log(text.slice(1, 1 + -2)); // '123'
console.log(text.substring(1, 1 + -2)); // '0'
Para una cadena y enteros seguros, ajusta el inicio a los límites de la cadena antes de aplicar la longitud. Una longitud negativa pasa a cero y una excesiva se limita a las unidades restantes.
{
function sliceWithLength(text, start, length) {
const from = start < 0
? Math.max(text.length + start, 0)
: Math.min(start, text.length);
if (length === undefined) return text.slice(from);
const count = Math.min(Math.max(length, 0), text.length - from);
return text.slice(from, from + count);
}
console.log(sliceWithLength('123456789', -2, 5)); // '89'
console.log(sliceWithLength('123456789', 1, -2)); // ''
console.log(sliceWithLength('123456789', 3)); // '456789'
}
Las salidas son '89', una cadena vacía y '456789'. La función espera una cadena y enteros seguros, con longitud opcional. Si el código existente admite cadenas, fracciones o infinitos como argumentos, conserva también sus reglas de conversión.




