How do I filter with Regex and javascript?

I have text in an element on my page and I want to drop the price on that page without any text.

I found the page contains a price like this:

<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 simple or asked in a different way, but I don't know anything about regular expressions, so I asked you to help :).

0


a source to share


4 answers


<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 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>

      



+4


a source


document.evaluate("//span[@class='discount']", 
  document, 
  null, 
  XPathResult.ANY_UNORDERED_NODE_TYPE, 
  null).singleNodeValue.textContent.replace("now $", "");

      



EDIT: This is standard XPath . I don't know what explanation you are looking for. For older browsers, you will need a third party library like Sarissa and / or Java-line .

+3


a source


Regexes are fundamentally bad at parsing HTML (see Can you give some examples of why it is difficult to parse XML and HTML with regex? For what). You need an HTML parser. See Can you give an example of parsing HTML with your favorite parser? for examples using various parsers.

The answers by Patrick McElhany and Matthew Flashen are a good way to solve the problem.

+1


a source


as suggested by Matthew Flaschen , XPATH is the best way to go if you know something about the node structure of the target document (and since you provided For example, you seem to be). If you don't know the structure of node, regexes are still lousy for parsing XML.

a few more resources to get you started:

I also found the FireFox DOM Inspector and XPather extension command - an invaluable tool for getting and testing XPath expressions on this page. (If you're using a different browser - well, I don't know).

0


a source







All Articles