Search code examples
jqueryregexappendhref

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


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]
});

Solution

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