如果 URL 包含 6 位数字,则将值附加到 class

If URL contains 6 digit number append the value to a class

如果有人回答了这个问题,我深表歉意。我尝试过搜索,但是对此很陌生,也许我没有使用正确的术语。

我有一个页面,其中包含指向以下 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,是否可以使用正则表达式和 JQuery 将这些值作为 class 添加到 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]
});

以上url:

$('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);
});

有几个错误:

  • 正则表达式已锚定:没有匹配项
  • 正则表达式初始化错误
  • 使用方法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}

您的代码存在一些问题:

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

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

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>

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