views:

95

answers:

1

By clicking on the "mylink" I want the link to be replaced by the number "123", which is extracted from parent tag. I think I'm not doing the ".match(...." right.

jQuery:

$(document).ready(function(){
  $(".link").click(function(){
    var comid = $(this).parents("div.comment").attr("class").match(/comment-([0-9]+)/)[1];
    $(".link").replaceWith(comid);
  });
});

html:

<div class="comment comment-123 ct">
  <div class="link">mylink</div>
</div>
A: 

You only have one matching so you need to use the 0th match (zero-based array). Also, it will return the entire match, so if you want just the number you'll need to remove the comment- text from it.

$(document).ready(function(){
  $(".link").click(function(){
    var comid = $(this).parents("div.comment")
                       .attr("class")
                       .match(/comment-[0-9]+/)[0]
                       .replace('comment-','');
    $(".link").replaceWith(comid);
  });
});

If there's a possibility that no match will occur, then you'd want to assign the matches to a variable and only do the replacement(s) if a match occurs (the variable is non-null).

tvanfosson
Yes, this did it, I was just working in drupal, so had to rewrite the parentheses. .replace('comment-',''); should be .replace("comment-",""); Thanks
timofey
I used single quotes for both, but double-quotes works, too.
tvanfosson