4

I have the following regex in javascript. I want to match a string so its product (,|x) quantity, each price. The following regex does this; however it returns an array with one element only. I want an array which returns the whole matched string first followed by product, quantity, each price.

// product,| [x] quantity, each price:
var pQe = inputText.match(/(^[a-zA-z -]+)(?:,|[ x ]?) (\d{0,3}), (?:each) ([£]\d+[.]?\d{0,2})/g);

(,|x) means followed by a comma or x, so it will match ice-cream, 99, $99 or ice-cream x 99, $99

How can I do that?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
heyumar
  • 51
  • 1
  • 4
  • 1
    It turns out I had to remove the /g, I changed it to /i. Thank you everyone anyway. Can someone please remove this question as I am not registered. – heyumar Jul 10 '11 at 00:03

1 Answers1

2

Use the exec function of the RegExp object. For that, you'll have to change the syntax to the following:

 var pQe = /(^[a-z ... {0,2})/g.exec(inputText)

Element 1 of the returned array will contain the first element of the match, element 2 will contain the second, and so on. If the string doesn't match the regular expression, it returns null.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • There is no need to switch to using exec. The match function that they were using also returns the array of matches. – jfriend00 Jul 10 '11 at 00:21