Jerry
Jerry

Reputation: 1109

Remove all characters after a comma with jQuery

I would like to remove all characters after the "," in a string using jQuery, by targeting the class of the element. Other solutions I found were using javascript, targeting the string itself instead of the class.

My code is:

<td class="priceinfo">€779,34&nbsp;</td>

How do I remove the characters after "," in the text of the td element?

Upvotes: 1

Views: 3024

Answers (5)

Rory McCrossan
Rory McCrossan

Reputation: 337743

You can use jQuery's text() method to achieve this. By providing a function as the argument to the method call that action will be performed on every element in the collection.

$('.priceinfo').text(function(i, t) {
  return t.substr(0, t.lastIndexOf(','));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr><td class="priceinfo">€779,34&nbsp;</td></tr>
  <tr><td class="priceinfo">€2,34&nbsp;</td></tr>
  <tr><td class="priceinfo">€1,290,34&nbsp;</td></tr>
</table>

The JS code can be made even more succinct if you use an ES6 arrow function, but note this is not supported in IE:

$('.priceinfo').text((i, t) => t.substr(0, t.lastIndexOf(',')));

Upvotes: 4

Smuuf
Smuuf

Reputation: 6544

Or you don't have to use a tank to hammer a nail and just use jQuery-free™ solution:

[].forEach.call(document.querySelectorAll('.priceinfo'), function (el) {
    var h = el.innerHTML;
    el.innerHTML = h.substr(0, h.indexOf(','));
});

Upvotes: 0

krishna
krishna

Reputation: 518

use below code

$('.priceinfo').html().split(",")[0]


below is the working fiddle

https://jsfiddle.net/5fwyjp52/1/

Upvotes: 3

Nutshell
Nutshell

Reputation: 8537

This way to do it remove all characters after the first comma:

$(function(){
    $('.priceinfo').each(function(){
      text = $(this).text();
      textSplit = text.split(',');
      $(this).text(textSplit[0]);
  });
});

See it here

Upvotes: 1

Pardeep Pathania
Pardeep Pathania

Reputation: 1538

you can try this :

str = str.substr(0, str.lastIndexOf(","));

Upvotes: 0

Related Questions