2

My apologies if this has been answered. I have tried searching however being fresh at this maybe I'm not using the right terminology.

I have a page with links to pdfs example below:

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

If a URL contains 6 digits (as above) and .pdf can these values be added to the href as a class using regex and JQuery? So the result being:

<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>

I have tried the following but no cigar

var regex = "^[0-9]{1,6}$";
$('a').each(function() {
    $(this).addClass(regex.match($(this).attr("href"))[0]
});
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
BentleyO
  • 35
  • 3

3 Answers3

2

There were several errors:

  • The regex was anchored: there was no match
  • The regex as wrongly initialized
  • Use the method exec instead of match
  • The JS was invalid (missing closing parenthesis)

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>

Also, if you meant exactly 6 digits, change regex to [0-9]{6}

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
2

There's a few problems with your code:

  1. Your regular expression, "^[0-9]{1,6}$"

This is saying you are expecting a number, 1 to 6 characters long, that is at the beginning of the string and is also the end. You are also setting is as a string, whereas you could use an actual expression:

var regex = /[0-9]{1,6}/g;
  1. regex.match is not a method.

You are calling match as a method on the regular expression, but it is actually the other way around. match is a method on Strings.

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

An update to your code could be as follows:

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>

There are a few ways you could improve this, including checking for the existence of the match before adding the class.

chazsolo
  • 7,873
  • 1
  • 20
  • 44
0

For the above 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);
});
Siva.G ツ
  • 831
  • 1
  • 7
  • 20