【问题标题】:Replace / append HREF filetype extension in Javascript在 Javascript 中替换/附加 HREF 文件类型扩展名
【发布时间】:2020-04-18 19:26:57
【问题描述】:

我一定是想多了。我需要选择类名称为cbs-Line1Link 的所有锚标记,如果它与文件类型(ppt、pptx、doc、docx 等)匹配,则将?Web=1 添加到 HREF 的末尾。所以,ppt 变成了pptx?Web=1

<a class="cbs-Line1Link" href="index.pptx">pptx title</a>
--------------------------------------------------------
const items = document.querySelectorAll(".cbs-Line1Link");
items.forEach(item => {
  let href = item.getAttribute("href")
  if (href.substring(href.length - 5) == '.pptx') {
    console.log(item)
    return item = item.getAttribute("href").replace(/\bpptx\b/, 'pptx?Web=1')
  }
})

jsfiddle

提前谢谢你!

【问题讨论】:

    标签: javascript replace foreach substring


    【解决方案1】:

    只需在条件中设置href。你不需要返回任何东西。示例:

    const items = document.querySelectorAll(".cbs-Line1Link");
    items.forEach(item => {
      let href = item.getAttribute("href");
      if (href.substring(href.length - 5) == '.pptx') {
        console.log(item);
        item.href = href + '?Web=1';
      }
    })
    &lt;a class="cbs-Line1Link" href="index.pptx"&gt;pptx title&lt;/a&gt;

    更好的是,由于您的扩展名的长度可能不同,您可以执行以下操作来更轻松地匹配所有扩展名:

    const items = document.querySelectorAll(".cbs-Line1Link");
    items.forEach(item => {
      const href = item.getAttribute("href");
      const extension = href.substring(href.lastIndexOf(".") + 1);
      if (['ppt', 'pptx', 'doc', 'docx'].includes(extension)) {
        console.log(item);
        item.href = href + '?Web=1';
      }
    })
    &lt;a class="cbs-Line1Link" href="index.pptx"&gt;pptx title&lt;/a&gt;

    【讨论】:

    • 我发誓我试过了,但没用。当然,这非常有效!谢谢!
    • @TimberHjellum 没问题,查看我的更新答案以获得更好的方法:)
    【解决方案2】:

    您可能需要考虑使用内置数组过滤器和映射函数。

    const items = [...document.querySelectorAll(".cbs-Line1Link")];
    items.filter( item => {
      const href = item.getAttribute("href");
      return href.substring(href.length - 5) === '.pptx'
    })
    .map( item => item.setAttribute("href", item.getAttribute("href") + '?Web=1'));
    &lt;a class="cbs-Line1Link" href="index.pptx"&gt;pptx title&lt;/a&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多