JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

$('.element span').each(function() {
  console.log($(this).text());
  var text = $(this).text().replace('N/A, ', '');
  $(this).text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">
  <span>N/A, Category</span>
</div>

Here’s another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

Leave a Comment

tech