JavaScript endsWith() 判断字符串是否以指定内容结尾

在 JavaScript 中,可以使用 text.endsWith(suffix) 判断字符串是否以指定的内容结尾。匹配时返回 true,否则返回 false。指定第二个参数 endPosition,可以只检查从开头截取的一段内容的末尾。

检查字符串末尾是否完全匹配

console.log('report.pdf'.endsWith('.pdf')); // true
console.log('report.PDF'.endsWith('.pdf')); // false
console.log('report.pdf '.endsWith('.pdf')); // false
console.log('abc'.endsWith('')); // true
try {
  'abc'.endsWith(/c/);
} catch (error) {
  console.log(error.name); // TypeError
}

比较时区分大小写,空格也参与匹配。空后缀始终匹配。如果要求用户必须输入后缀,请先检查输入值。将正则表达式作为搜索参数会抛出 TypeError。需要按模式匹配时,可以使用 RegExp.test()。比较规则见 ECMAScript · String.prototype.endsWith()。

用 endPosition 限定比较范围

endPosition 表示从开头算起要检查的长度。设为 3 时,范围包括索引 0、1 和 2。方法会将该值转换为整数,并限制在 0 到 text.length 之间。省略时使用整个字符串。

const text = 'abzcdz';
console.log(text.endsWith('z'));    // true   
console.log(text.endsWith('z', 2)); // false
console.log(text.endsWith('z', 3)); // true
console.log(text.slice(0, 3));     // 'abz'    

// endPosition
console.log(text.endsWith('z', 3.9));  // true
console.log(text.endsWith('z', -1));   // false
console.log(text.endsWith('z', 99));   // true
console.log('A🙂Z'.endsWith('🙂', 3)); // true
console.log('A🙂Z'.endsWith('🙂', 2)); // false

边界按 UTF-16 代码单元计数。'A🙂Z' 中的表情符号占两个代码单元,位置 3 包含完整的 'A🙂',位置 2 则从表情符号中间截断。如果界面让用户输入可见字符的个数,请先将其换算为代码单元的位置。

检查文件名和网址路径的后缀

先确定要检查的部分。判断网址的路径后缀时,用 new URL(address).pathname 取得路径,排除查询参数和片段。处理相对地址时,应提供基准网址,例如 new URL(path, base)。URL Standard · URL.pathname

console.log('report.pdf'.endsWith('.pdf')); // true
console.log('report.pdf?download=1'.endsWith('.pdf')); // false
const url = new URL('/report.pdf?download=1#preview', 'https://example.com');
console.log(url.pathname.endsWith('.pdf')); // true
console.log('REPORT.PDF'.toLowerCase().endsWith('.pdf')); // true

如果服务对 ASCII 扩展名不区分大小写,可以先把文件名转成小写,再与 .pdf 比较。后缀匹配仅说明文件名符合命名规则。接收上传时,仍需验证实际文件格式并执行服务器端策略。

在 HTML 示例中修改结束位置

将下面的代码以 UTF-8 编码保存为 string-ends-with.html,并在浏览器中打开。初始字符串 abzcdz 以 z 结尾,因此结果为 true。启用结束位置并保留 3,检查对象变为 abz,结果依然匹配。改为 2 后,检查对象是 ab,结果为 false。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>字符串后缀检查</title>
</head>
<body>
<label for="text">原始字符串</label>
<input id="text" type="text" value="abzcdz">
<label for="suffix">后缀</label>
<input id="suffix" type="text" value="z">
<label><input id="use-end" type="checkbox"> 使用结束位置</label>
<label for="end">结束位置</label>
<input id="end" type="number" min="0" step="1" value="3" disabled>
<pre id="output" aria-live="polite"></pre>
<script>
const text = document.querySelector('#text');
const suffix = document.querySelector('#suffix');
const useEnd = document.querySelector('#use-end');
const end = document.querySelector('#end');
const output = document.querySelector('#output');

function show() {
  const value = text.value;
  const target = suffix.value;
  end.disabled = !useEnd.checked;
  const position = Number(end.value);
  if (useEnd.checked && (end.value.trim() === '' ||
      !Number.isInteger(position) || position < 0)) {
    output.textContent = "请输入大于或等于零的整数。";
    return;
  }
  const checked = useEnd.checked ? value.slice(0, position) : value;
  const result = useEnd.checked
    ? value.endsWith(target, position) : value.endsWith(target);
  output.textContent = `检查对象: ${JSON.stringify(checked)}\n` +
    `查找的后缀: ${JSON.stringify(target)}\n` +
    `endsWith() 结果: ${result}`;
}

text.addEventListener('input', show);
suffix.addEventListener('input', show);
useEnd.addEventListener('change', show);
end.addEventListener('input', show);
show();
</script>
</body>
</html>

在启用结束位置的情况下清空数字框,就会显示输入提示。关闭该选项后会重新检查整个字符串。示例不接受负数或小数,方法本身会将数值转换为整数并限制在有效范围内。也可以清空后缀,观察空字符串的匹配结果。