1

I have a page with links like:

<a class="mod-articles-category-title " href="curso-bsc/82-balanced-scorecard/o-bsc-uma-ferramenta-para-melhorar-a-performance-da-organizacao/377-responsabilizacao-e-trabalho-de-equipa">

<a class="mod-articles-category-title " href="curso-bsc/82-balanced-scorecard/o-bsc-uma-ferramenta-para-melhorar-a-performance-da-organizacao/378-recompensas-e-incentivos-baseados-no-bsc">

<a class="mod-articles-category-title " href="curso-bsc/82-balanced-scorecard/o-bsc-uma-ferramenta-para-melhorar-a-performance-da-organizacao/99-vantagens-do-bsc-gestao-da-mudanca">

I need an array with the numbers after the last slash (/) and the following minus (-):

"377", "378", "99"

I'm using:

links=$('.mod-articles-category-title').attr('href');

But I'm missing the expression to get those numbers into the array. Can someone help?

3 Answers 3

3

This should do the job, allthough it is untested:

arr = new Array();
$('.mod-articles-category-title').each(function(){
  parts = $(this).attr("href").split("/");
  part = parts[parts.length-1]
  parts = part.split("-");
  part = parts[0];
  arr.push(part);
});

For more information see:

http://api.jquery.com/each/ - About jQuery each function

http://www.w3schools.com/jsref/jsref_split.asp - About JavaScript split function

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks I tested it and it is returning the first digit of the numbers I'm searching. In my example: "3","3","9"
0
var links = [];
$('a.mod-articles-category-title').each(function () {
    links.push($(this).attr('href').match(/(\d+)/g)[1]);
});
console.log(links);

jsFiddle example

5 Comments

It worked, I just need to check reg expressions reference to understand it. Thanks a lot for your help.
Hi, it doesn't seem to be working when the number has more or less than 3 digits. I get the error: TypeError: $(...).attr(...).match(...) is null
Seems to work fine in the fiddle. The last link has a two digit number.
Hi, sorry, the problem is some hrefs don't have the slash(/). In that case, they have the id number like: a href="127-importacao-de-dados". I created an if statement to filter those cases but I don't know the reg expression to use inside the match function. If you could advise, I'd be thankful.
The difference there would be to use match(/(\d+)/g)[0] instead of match(/(\d+)/g)[1] (zero versus one).
0
var numbers = $('.mod-articles-category-title').map(function()
{
    return $(this).attr('href').match(/\/(\d+)-[^/]*$/)[1];
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.