views:

372

answers:

6

I have the following HTML:

<span id="UnitCost5">$3,079.95 to $3,479.95</span>

And i want to use Javascript and Regex to get all number matches.

So i want my script function to return: 3,079.95 AND 3,479.95

Note the text may be different so i need the solution as generic as posible, may be it will be like this:

<span id="UnitCost5">$3,079.95 And Price $3,479.95</span>
+2  A: 

All the numbers would be matched by:

\.?\d[\d.,]*

This assumes the numbers you look for can start with a decimal dot. If they cannot, this would work (and maybe produce less false positives):

\d[\d.,]*

Be aware that different local customs exist in number formatting.

I assume that you use appropriate means to get hold of the text value of the HTML nodes you wish to process, and that HTML parsing is not part of the excercise.

Tomalak
I wrote it var prices = myElement.innerHTML.match(/\.?\d[\d.,]*/g);and /g to get all prices not just the first one.
Amr ElGarhy
I suggest you use innerText (or textContent) unless you are absolutely sure that innerHTML cannot contain any HTML code. If you have a JavaScript library in place, you can use that to get hold of the text content browser-independently.
Tomalak
A: 

A very simple solution is the following one. Note that it will also match some invalid number strings like $..44,.777.

\$[0-9,.]+
Daniel Brückner
A: 
(function () {
    var reg = /\$([\d\.,]+)\s[\w\W]+\s\$([\d\.,]+)$/;


    // this function used to clean inner html
    function trim(str) {
        var str = str.replace(/^\s\s*/, ''),
         ws = /\s/,
         i = str.length;
        while (ws.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    }

    function getNumbersFromElement(elementId) {
        var el = document.getElementById(elementId),
            text = trim(el.innerHTML), 
            firstPrice,
            secondPrice,
            result;

        result = reg.exec(text);

        if (result[1] && result[2]) {
            // inside this block we have valid prices
            firstPrice = result[1];
            secondPrice = result[2];
            // do whatever you need
            return firstPrice + ' AND ' + secondPrice;
        } else {
            return null; // otherwise 
        }
    }
    // usage:
    getNumbersFromElement('UnitCost5');
})();
Alexander Ulizko
A: 

You don't want to capture all numbers, otherwise you would get the 5 in the id, too. I would guess, what you're looking for is numbers looking like this: $#,###.##

Here goes the expression for that:

/\$[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?/
  • \$ The dollar sign
  • [0-9]{1,3} One to three digits
  • (,[0-9]{3})* [Optional]: Digit triplets, preceded by a comma
  • (\.[0-9]+)? [Optional]: Even more digits, preceded by a period
soulmerge
A: 

The following will return an array of all prices found in the string

function getPrices(str) {
    var reg = /\$([\d,.]+)/g;
    var prices =[];
    var price;
    while((price = reg.exec(str))!=null) {
        prices.push(price);
    }
    return prices;
}

edit: note that the regex itself may return some false positives

Jonathan Fingland
+1  A: 
/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;

Let's break that into parts for explanations:

  • (?:\d{1,3},)* - Match any numbers separated by a thousand-divider
  • \d{1,3} - Match the numbers before the decimal point
  • (?:.\d+) - Match an arbitrary number of decimals
  • Flag 'g' - Make a global search to find all matches in the string

You can use it like this:

var regex = /(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
var numbers = "$3,079.95 And Price $3,479.95".match(regex);
// numbers[0] = 3,079.95
// numbers[1] = 3,479.95
PatrikAkerstrand
That would match the string 1,1,1,1.0
soulmerge