Amr Elgarhy Amr Elgarhy - 29 days ago 6
HTML Question

How to filter using Regex and javascript?

I have some text in an element in my page, and i want to scrap the price on that page without any text beside.

I found the page contain price like that:

<span class="discount">now $39.99</span>


How to filter this and just get "$39.99" just using JavaScript and regular expressions.

The question may be too easy or asked by another way before but i know nothing about regular expressions so asked for your help :).

Answer
<script language="javascript">
window.onload = function () {

    // Get all of the elements with class name "discount"
    var elements = document.getElementsByClassName('discount');

    // Loop over each <span class="discount">
    for (var i=0; i < elements.length; i++) {

         // get the text, e.g. "now $39.99"
         var rawText = elements[i].innerHTML;

         // Here's a regular expression to match one or more digits (\d+)
         // followed by a period (\.) and one or more digits again (\d+)
         var priceAsString = rawText.match(/\d+\.\d+/)

         // You'll want to make the price a floating point number if you 
         // intend to do any calculations with it.
         var price = parseFloat(priceAsString); 

         // Now what do you want to do with the price? I'll just write it out
         // to the console (using FireBug or something similar)
         console.log(price);

    }
}
</script>