【问题标题】:If URL contains 6 digit number append the value to a class如果 URL 包含 6 位数字,则将该值附加到一个类
【发布时间】:2017-08-09 02:27:55
【问题描述】:

如果此问题已得到答复,我深表歉意。我尝试过搜索,但是对此感到新鲜,也许我没有使用正确的术语。

我有一个页面,其中包含以下 pdf 示例的链接:

<a href="https://www.pdflinks.com/files/190488/nameoffile.pdf">Link1</a>
<a href="https://www.pdflinks.com/files/112254/nameoffile.pdf">Link2</a>

如果 URL 包含 6 位数字(如上)和 .pdf,是否可以使用 regex 和 JQuery 将这些值作为类添加到 href 中?所以结果是:

<a href="https://www.pdflinks.com/files/190488/nameoffile.pdf" class="pdf190488">Link1</a>
<a href="https://www.pdflinks.com/files/112254/nameoffile.pdf" class="pdf112254">Link2</a>

我尝试了以下但没有雪茄

var regex = "^[0-9]{1,6}$";
$('a').each(function() {
    $(this).addClass(regex.match($(this).attr("href"))[0]
});

【问题讨论】:

    标签: jquery regex append href


    【解决方案1】:

    有几个错误:

    • 正则表达式已锚定:没有匹配项
    • 正则表达式初始化错误
    • 使用方法exec 而不是match
    • JS 无效(缺少右括号)

    var regex = /[0-9]{1,6}/;
    $('a').each(function() {
      $(this).addClass('pdf' + regex.exec($(this).attr("href"))[0]);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <a href="https://www.pdflinks.com/files/190488/nameoffile.pdf">Link1</a>
    <a href="https://www.pdflinks.com/files/112254/nameoffile.pdf">Link2</a>

    另外,如果您的意思是正好是 6 位数字,请将正则表达式更改为 [0-9]{6}

    【讨论】:

    【解决方案2】:

    您的代码存在一些问题:

    1. 你的正则表达式,"^[0-9]{1,6}$"

    这是说您期待一个数字,长度为 1 到 6 个字符,它位于字符串的开头,也是结尾。您还将 is 设置为字符串,而您可以使用实际表达式:

    var regex = /[0-9]{1,6}/g;
    
    1. regex.match 不是方法。

    您正在调用match 作为正则表达式的方法,但实际上是相反的。 match 是一个字符串方法。

    $(this).attr('href').match(regex)[0]
    

    对您的代码的更新可能如下:

    var regex = /[0-9]{1,6}/g;
    
    $('a').each(function() {
      var $this = $(this);
      $this.addClass('pdf' + $this.attr('href').match(regex)[0]);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="https://www.pdflinks.com/files/190488/nameoffile.pdf">Link1</a>
    <a href="https://www.pdflinks.com/files/112254/nameoffile.pdf">Link2</a>

    有几种方法可以改进这一点,包括在添加类之前检查匹配是否存在。

    【讨论】:

    • 感谢 chazsolo 的解释和替代解决方案。
    【解决方案3】:

    以上网址:

    $('a').each(function() {
      var path = $(this).attr("href");
      var str = path.split("/");
      var fileName = str[5].split(".");
      var className = fileName[1]+str[4];
      $(this).addClass(className);
    });
    

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 1970-01-01
      • 2021-09-10
      • 2011-08-25
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      相关资源
      最近更新 更多