Search code examples
javascriptstringsummultiplication

JavaScript - Select a class then remove the pound sign and then perform a sum


I'm using the chrome console to attempt to create a string to do the following: Take the price from a page & multiply it.

I've got this far, but I am at a basic level in JavaScript.

document.querySelector(".classname").innerHTML;

&

.replace(/\u00A3/g, '');

However I am not sure how to combine these 2 strings so that once it finds the price with the first string it then removes the pound sign with the second, any assistance would be very appreciated!

If you're not understanding what I mean then I am very sorry!


Solution

  • Take a look at this code:

    function parsePrice(elem) {
        return parseFloat(elem.innerHTML.replace(/[^0-9\.]+/g,"")); //remove anything that is not a digit or dot
    }
    
    document.querySelectorAll('.test').forEach(function(elem){
      elem.innerHTML = '£'+parsePrice(elem)*4
    });
    <div class="test">£75</div>
    <div class="test">£15</div>
    <div class="test">£25</div>