将 JavaScript 的 substr() 迁移到 slice() 或 substring()

text.substr(start, length) 从指定位置取出一定长度的子字符串。这是为 Web 兼容保留的旧功能。slice() 和 substring() 的第二个参数是结束索引。

将第二个参数理解为长度

索引从零开始。对 '123456789' 调用 substr(1, 5) 得到 '23456'。省略长度会取到末尾,原字符串不变。请参阅 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'

处理负数起点和边界

负数起点从末尾计算,过小则限制为零。长度不大于零,或起点达到或超过末尾时,返回空字符串。按 UTF-16(16 位 Unicode 转换格式)代码单元计数,可能拆开表情符号。

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)); // ''

运行完整的旧方法与 slice 比较

将示例以 UTF-8 保存为 substr-example.html 并打开。两种方法最初都得到 '23456'。长度留空会取到末尾。起点为负数时只显示旧方法结果和提示,因为简化比较仅使用非负整数。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较 substr 和 slice</title>
</head>
<body>
<label for="source">原始字符串</label>
<input id="source" type="text" value="123456789">
<label for="start">起始索引</label>
<input id="start" type="number" step="1" value="1">
<label for="length">长度(留空表示取到末尾)</label>
<input id="length" type="number" step="1" value="5">
<button id="run" type="button">比较</button>
<button id="reset" type="button">重置</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 = '起点和长度请输入安全整数。长度可以留空。';
    return;
  }
  const oldResult = count === undefined
    ? source.value.substr(s)
    : source.value.substr(s, count);
  let alternative = '转换负数参数前请检查输入范围。';
  if (s >= 0 && (count === undefined || count >= 0)) {
    const newResult = count === undefined
      ? source.value.slice(s)
      : source.value.slice(s, s + count);
    alternative = `slice() 结果: ${JSON.stringify(newResult)}`;
  }
  output.textContent = `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>

迁移到 slice() 或 substring()

起点和长度均为非负整数时,slice(start, start + length) 可得到相同结果。其他值可能不同。slice() 的负结束索引从末尾计算。substring() 会把负数调整为零并交换顺序颠倒的边界。请参阅 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'

对于字符串和安全整数,先把起点限制在字符串范围内,再应用长度。负长度按零处理,过长则限制为剩余代码单元。

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

输出依次为 '89'、空字符串和 '456789'。函数假设输入为字符串和安全整数,长度可以省略。如果旧接口接受字符串、小数或无穷值作为参数,应另行保留其转换规则。