1

I am trying to get the content that I get back from a response. The content is within a div tag, but when T try to run the regex I don't get anything when I display it. If I use a regex tester I get the content I want. Below is the code I am using:

var myString = "<div class="zdc-box zdc-error">
Unknown column 'order_numbe' in 'field list'
</div>"
var myRegexp = "/<div class=\"zdc-box zdc-error\">\s+(.*)\s+.*?</div>/";
var match = myRegexp.exec(myString);
alert(match[1]); 

Can anybody help me and let m know what i am doing wrong?

zeid10
  • 511
  • 8
  • 28
  • 1
    [Just don't parse HTML with regex](http://stackoverflow.com/a/1732454/1249581). – VisioN Dec 20 '13 at 13:52
  • 1
    that's a response from an ajax call. – zeid10 Dec 20 '13 at 13:57
  • for what \s+(.*)\s+ ? [greedy](http://stackoverflow.com/a/2301298/3110638) part – Jonny 5 Dec 20 '13 at 14:02
  • @VisioN - Do you realize that the first answer to that question doesn't really explain *why* you shouldn't parse HTML, and the second answer says parsing a limited set of HTML (as in the OP's question) is **ok**? – JDB Dec 20 '13 at 16:20

3 Answers3

1

Revised answer below using exec and groupings (thanks @JDB)

var myString = "<div class=\"zdc-box zdc-error\">Unknown column 'order_numbe' in 'field list'</div>"
var myRegexp = new RegExp("<div class=\"zdc\-box zdc-error\">(.*?)</div>", "g")
var match = myRegexp.exec(myString);
alert(match[1]);
John Lay
  • 301
  • 4
  • 12
  • John that returns the following:
    Unknown column 'order_numbe' in 'field list'
    . I need what is inside the
    tag. thank you.
    – zeid10 Dec 20 '13 at 14:18
1

sorry for not answering your question in a way you'd probably expect, but using a regex seems like the wrong approach. What you really want to do is to convert your html snippet into a DOM element and then parse its content:

var element = document.createElement("div");
element.innerHTML = "<div class='zdc-box zdc-error'>Unknown column 'order_number' in 'field list'</div>";
var myString = element.querySelector('.zdc-box').innerHTML;
alert(myString);

This is a much (much) cleaner approach. Obviously, there are more ways to get to the content than with querySelector, this is just one of many…

Edit: for example: element.childNodes...

auco
  • 9,329
  • 4
  • 47
  • 54
0

you can try this:

var myRegexp = /<div class="zdc-box zdc-error">\s*([\s\S]*?)\s*<\/div>/;
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125