JavaScript substr(): Move legacy code to slice() or substring()

text.substr(start, length) takes a substring of the specified length from the starting position. It is a legacy feature for web compatibility. slice() and substring() take an end index as their second argument.

Read the second argument as a length

Indexes start at zero. For '123456789', substr(1, 5) returns '23456'. Omitting the length takes the remainder, and the source is unchanged. See 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'

Handle negative starts and boundaries

A negative start counts from the end. Very negative starts clamp to zero. A length of zero or less, or a start at or past the end, gives an empty string. Units are UTF-16 (16-bit Unicode Transformation Format) code units, so the result can split an 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)); // ''

Try a complete legacy and slice comparison

Save the complete example as substr-example.html in UTF-8 and open it. The default result is '23456' with both methods. Leave length blank to take the remainder. A negative start shows only the legacy result and a message, because the simple comparison uses nonnegative integers.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Compare substr and slice</title>
</head>
<body>
<label for="source">Original string</label>
<input id="source" type="text" value="123456789">
<label for="start">Start index</label>
<input id="start" type="number" step="1" value="1">
<label for="length">Length (blank for the remainder)</label>
<input id="length" type="number" step="1" value="5">
<button id="run" type="button">Compare</button>
<button id="reset" type="button">Reset</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 = 'Enter safe integers for start and length. The length may be blank.';
    return;
  }
  const oldResult = count === undefined
    ? source.value.substr(s)
    : source.value.substr(s, count);
  let alternative = 'Review the input range before converting negative arguments.';
  if (s >= 0 && (count === undefined || count >= 0)) {
    const newResult = count === undefined
      ? source.value.slice(s)
      : source.value.slice(s, s + count);
    alternative = `slice() result: ${JSON.stringify(newResult)}`;
  }
  output.textContent = `substr() result: ${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>

Migrate to slice() or substring()

For nonnegative integer start and length, slice(start, start + length) can reproduce substr(). For other inputs the behavior can differ. slice() counts negative end positions from the end. substring() treats negative values as zero and swaps reversed bounds. See 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'

For a string and safe integer arguments, normalize the start within the string before applying the length. Clamp a negative length to zero and an oversized length to the remaining characters, measured in code units.

{
  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'
}

The outputs are '89', an empty string, and '456789'. The helper assumes a string and safe integer arguments, with length optional. If the old function accepted strings, fractions, or infinities as arguments, preserve those conversion rules separately.