给某个资源的链接,如 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()。