← 返回完整题库
JavaScript简单

给某个资源的链接,如 https://www.baidu.com/index.html ,请实现一个方法,获取该资源的后缀,如 html

参考答案

function getExt(url) {
  try {
    const path = new URL(url).pathname;
    const m = path.match(/\.([a-zA-Z0-9]+)$/);
    return m ? m[1] : '';
  } catch { return ''; }
}

要点:

  • 用 URL 解析,能自动剔除 query 与 hash;
  • 无后缀、目录结尾(/a/)返回空串;
  • 多后缀(.tar.gz)按需取最后一段或全部;
  • 大小写统一可 toLowerCase()。

本题来自 计算机知识面试题库,共 921 道题。