Neophile
Neophile

Reputation: 5860

Remove the vertical spacers in a td

What is the best way to remove the last occurrence of the element spacer (|) from this td using jQuery?

 <td class="actionCol" nowrap=""><a href="#xyz">XYZ</a> | <a href="#err">ERR</a> | <a href="#PING">PING</a></td>

Upvotes: 0

Views: 80

Answers (2)

Tushar
Tushar

Reputation: 87203

You can replace the last occurrence using substr. No need to use regex, this will be faster than regex.

$('.actionCol').html(function(i, e) {
  var lastIndex = e.lastIndexOf('|');
  return e.substr(0, lastIndex) + e.substr(lastIndex + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
  <td class="actionCol" nowrap=""><a href="#xyz">XYZ</a> | <a href="#err">ERR</a> | <a href="#PING">PING</a>
  </td>
</table>

Upvotes: 1

lshettyl
lshettyl

Reputation: 8171

So, to remove only the last occurrence, you may do the following.

$('.actionCol').html(function(_, elem) {
    return elem.replace(/\|(?!.*\|)/, '');
});

A Demo

Upvotes: 1

Related Questions