Reputation: 5758
I'm not sure where I'm going wrong but I'm trying to remove a € symbol from a String using jQuery
as I'd like to be able to add the Values to a shopping cart.
Anyways, this is my fiddle: https://jsfiddle.net/javacadabra/uuu8px6r/1/
I'm calling the javascript replace
function on a variable which I presume shouldn't matter?
If anyone can't see my fiddle
this is the html
:
<div id='shopping-cart'>
<span><span id='s-qty'>0</span> Items in Cart</span>
<span>€<span id='s-total'>0.00</span></span>
</div>
<p class="book-price">€7.99</p><div class='add-to-cart'>Add to Cart</div>
and my jquery
:
var cartitems = 0;
$('.add-to-cart').click(function(){
var bookprice = $(this).parent().find('.book-price').text();
bookprice.replace('€', '');
cartitems = parseFloat(cartitems + 1);
price = bookprice;
$('#s-qty').html(cartitems);
$('#s-total').html(price)
});
The above code is giving me the following output:
€€7.99 (the euro symbol is never being removed).
Probably a trivial question, so apologies but I'm at a loss so would appreciate any help.
Thank you.
Upvotes: 0
Views: 7808
Reputation: 31949
The replace
does not mutate the string it is executed on, the new value is returned instead. You need to store it in a variable.
bookprice = bookprice.replace('€', '');
In your case:
price = bookprice.replace(/€|&euro/g, '')
This solution uses regular expressions to replace both €
and html encoded &euro
if present.
Upvotes: 1
Reputation: 16041
The replace
function is not an in-place operation in JavaScript, as strings are immutable. The following line replace the €
symbol and the €
HTML special character:
bookprice = bookprice.replace('€', '').replace('€', '');
Upvotes: 1
Reputation: 334
bookprice = bookprice.replace('€', '');
works correctly, or
var bookprice = $(this).parent().find('.book-price').text().replace('€', '');
Upvotes: 1