1

(This is greasemonkey with jquery)

I have a string of data which is retrieved with
$.post('page.php',function (data) { ... });
In that data, there are html tags like
<option value='numeric'>data</option> along with random, useless information.
I want to be able to loop through each match and get the numeric value and the data between the option tags.
How would I do this? I tried:
reg = new RegExp(/<option value=\'(.+?)\'>(.+?)<\/option>/);
var result;
while (result = reg.exec(data)) {
GM_log(result);
}

However, that returns all sorts of failures. What am I doing wrong?

3 Answers3

0

First problem I can see is that you are passing RegExp constructor a literal regex object. This is not a problem as such, but there is no point to using RegExp constructor if you can do it using a regex literal.

You can use RegExp constructor like this

reg = new RegExp("<option value='(.+?)'>(.+?)<\/option>");

or alternatively you can use a regex literal like this

reg = /<option value='(.+?)'>(.+?)<\/option>/;

Now

reg.exec("<option value='numeric'>data</option>") 

gives

["<option value='numeric'>data</option>", "numeric", "data"]

Finally parsing html with regular expressions is not a good idea. More on that here RegEx match open tags except XHTML self-contained tags

Community
  • 1
  • 1
Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43
0
$.post('page.php',function (data) { 
   alert($(data).find('option').attr('value')); 
   // returns numeric if there is one element. so use a .each() to get individual ones.

});
Val
  • 17,336
  • 23
  • 95
  • 144
0

try using /g in the pattern Object.

I've tested this with sample code below:

<html>
   <body>
     <script type="text/javascript">

           var str="Hello world Hello World Heello you! ";
           //look for "Hello"
           var patt=/Hello/g;
           var resulT
           while(result=patt.exec(str)){
             document.write("Returned value: " +  result); 
             var result=patt.exec(str);
             document.write("<br />Returned value: " +  result); 
           }
       </script>
    </body>
</html>
Amit Gupta
  • 577
  • 4
  • 14