You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript函数兼容带路径与仅文件名的MP4视频播放?

解决方案:兼容带路径和不带路径的文件名

没问题,这个需求很常见——我们只需要精准提取文件名部分,就能让函数同时兼容x.mp4和a/x.mp4这两种格式。下面给你几个实用的方案:

方案1:用split处理路径(简单直接)

核心思路是先通过split('/').pop()提取最后一段(也就是文件名),再去判断后缀。这个方法代码简洁,适合大多数日常场景:

function PlayWordFile(fileNam) {
  if (fileNam === "") {
    alert('No file attached.');
    return;
  }
  // 提取文件名:不管前面有没有路径,取最后一个/之后的部分
  const fileName = fileNam.split('/').pop();
  // 提取后缀并转小写,避免大小写不匹配(比如MP4、Mp4)
  const extn = fileName.split('.').pop().toLowerCase();
  
  if (extn === "mp4") {
    const video = document.getElementById('videoPlayer');
    video.pause();
    video.removeAttribute('src');
    video.load();
    
    const source = document.createElement('source');
    // 用提取到的纯文件名拼接路径,确保最终src是正确的
    source.setAttribute('src', `/x/${fileName}`);
    video.appendChild(source);
    video.play();
  }
}

如果需要兼容Windows系统的\路径分隔符,可以把split('/')改成split(/[\/\\]/),这样不管是/还是\都能正确分割。

方案2:用URL API(健壮性更强)

如果你的场景可能遇到绝对路径、带查询参数的路径(比如https://example.com/path/x.mp4?t=123),用浏览器原生的URL API会更靠谱,它能自动处理各种复杂路径:

function PlayWordFile(fileNam) {
  if (fileNam === "") {
    alert('No file attached.');
    return;
  }
  // 构造URL对象,自动解析路径
  const url = new URL(fileNam, window.location.origin);
  // 从路径中提取最后一段文件名
  const fileName = url.pathname.split('/').pop();
  const extn = fileName.split('.').pop().toLowerCase();
  
  if (extn === "mp4") {
    const video = document.getElementById('videoPlayer');
    video.pause();
    video.removeAttribute('src');
    video.load();
    
    const source = document.createElement('source');
    source.setAttribute('src', `/x/${fileName}`);
    video.appendChild(source);
    video.play();
  }
}

方案3:正则表达式(灵活定制)

如果你喜欢用正则,也可以直接匹配最后一个/之后的所有字符,快速拿到文件名:

function PlayWordFile(fileNam) {
  if (fileNam === "") {
    alert('No file attached.');
    return;
  }
  // 正则匹配:取最后一个/之后的部分(如果没有/就取整个字符串)
  const fileNameMatch = fileNam.match(/[^\/]+$/);
  if (!fileNameMatch) {
    alert('Invalid file path.');
    return;
  }
  const fileName = fileNameMatch[0];
  const extn = fileName.split('.').pop().toLowerCase();
  
  if (extn === "mp4") {
    const video = document.getElementById('videoPlayer');
    video.pause();
    video.removeAttribute('src');
    video.load();
    
    const source = document.createElement('source');
    source.setAttribute('src', `/x/${fileName}`);
    video.appendChild(source);
    video.play();
  }
}

额外提示

我还加了.toLowerCase()处理后缀,这样能兼容MP4、Mp4这类大小写混合的格式,让函数更鲁棒。

内容的提问来源于stack exchange,提问作者Atul Mathew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:37:58