i'm trying to learn regex parse in javascript.
I need to read the text in a "span"
<span class="item_color_title">Status:</span>
<span class="item_color_success">
Alive
</span>
"Alive" is what i need. Any easy way out?
This is for a firefox extension, where i've:
var req = new XMLHttpRequest();
req.open('GET', 'http://www.example.com/', false);
req.send(null);
if(req.status == 200)
standard_status.label = req.responseText;
And, standard_status should say "Alive"
Thanks!!
-
5You should not use regex to parse html :)dotoree– dotoree2012年03月06日 19:00:06 +00:00Commented Mar 6, 2012 at 19:00
4 Answers 4
Parse the response into an HTML fragment:
> html = $('<div/>').html(req.responseText)
> $('.item_color_success', html).text()
"Alive"
1 Comment
responseText is the HTML and that it hasn't been attached to the DOMRegex? jQuery makes it trivial:
alert($('span.item_color_success').html());
4 Comments
standard_status.label = $('div.item_color_success').html(). but you should maybe use .text() instead of .html()Well, if you really want to use a regexp you could use this:
var text = req.responseText.replace('\n', '')
, status = text.match(/<span class="item_color_success">(.*)<\/span>/)[1]
standard_status.label = status
You need to replace the linebreaks as js is not correctly matching linebreaks with .* in combination with /.*/m.
Hope that helps.
If you don't wat to add an extra Jquery dependency, this can be done with pure Javascript.
var req = new XMLHttpRequest();
req.onload = function() {
alert(this.responseXML.title);
if(req.status == 200){
standard_status.label = req.responseXml.getElementsByClassName('item_color_success')[0].textContent;
}
}
req.open("GET", 'http://www.example.com/'); //must use async request for HTML
req.responseType = "document";
req.send();
I didn't test this but it should not be too far off.