How to extract a value from an element and, optionally, round it

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

This JavaScript snippet will extract a price from a DOM element, remove all alphanumeric characters, such as currency or symbols or other words, and return it.

The second snippet will also round the value.

let price,

// Extract value
price = document.getElementById('price');
priceValue = parseInt(price.innerText.replace(/[^0-9.]/g, ''));

document.getElementById('result').innerHTML = priceValue;

// Extract value and round it
price = document.getElementById('price');
priceRounded = parseFloat(price.innerText.replace(/[^0-9.]/g, '')).toFixed(2);

document.getElementById('result-rounded').innerText = priceRounded;

See a fiddle here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

👋 Added by Ciprian on Thursday, August 22, 2019 in JavaScript. Last modified on Thursday, August 22, 2019.


Contribute to this article by sharing your opinion on Twitter:

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started
Privacy Policy