Home > Software engineering >  jQuery replacing string
jQuery replacing string

Time:05-16

I have the following html. I need a jquery function that replaces just the string 'Price' with a different string. I tried text(), html(). But didn't work.

<div  style="">
Price: <span >$160.00</span> — <span >$15,950.00</span>
</div>

I tried: jQuery('div.price_label).text('newstring') jQuery('div.price_label).first().text('newstring')

But didn't work. jQuery gets the selector ok. but the whole div is replaced. Not just string 'Price'. Please help!!

CodePudding user response:

const priceLabel = $('.price_label')[0]
priceLabel.innerHTML = priceLabel.innerHTML.replace("Price: ", "")
<script
  src="https://code.jquery.com/jquery-3.6.0.js"
  integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
  crossorigin="anonymous"></script>
<div  style="">
Price: <span >$160.00</span> — <span >$15,950.00</span>
</div>

CodePudding user response:

This work fine:

$(".price_label").text(function(index, text) { 
    return text.replace('Price', 'New Price'); 
});
  • Related