Home » Jquery » jquery – Remove last instance of string from an element's text

jquery – Remove last instance of string from an element's text

Posted by: admin February 22, 2020 Leave a comment

Questions:

I am trying to to cut the last CHF text out of the div. I couldn’t get this to work.

$(document).ready(function() {
  var myval = $(".gui-big.guy-price strong").text();
  console.log(myval);
  myval = myval.substring(0, myval.length - 3);
  $("div.gui-big.guy-price strong").val(myval);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gui-item gui-big">
  <div class="gui-desc">
    <strong>Gesamt inkl. MwSt:</strong>
  </div>
  <div class="gui-price">
    <strong>CHF53,70 CHF</strong>
  </div>
How to&Answer:

Firstly note that your selectors are incorrect. It has a typo, and requires spaces to indicate that you’re looking for child elements.

To replace the last occurence of one string within another you can use a regular expression. To make this more succinct you can provide a function to text() which accepts the current value as an argument and returns the new value to be set. Try this:

$(document).ready(function() {
  $('.gui-big .gui-price strong').text((i, t) => t.replace(/CHF([^CHF]*)$/, '$1'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gui-item gui-big">
  <div class="gui-desc">
    <strong>Gesamt inkl. MwSt:</strong>
  </div>
  <div class="gui-price">
    <strong>CHF53,70 CHF</strong>
  </div>
</div>