Reputation: 1546
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!!
Upvotes: 0
Views: 235
Reputation: 7351
Regex? jQuery makes it trivial:
alert($('span.item_color_success').html());
Upvotes: 2
Reputation: 69934
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.
Upvotes: 0
Reputation: 177530
Parse the response into an HTML fragment:
> html = $('<div/>').html(req.responseText)
> $('.item_color_success', html).text()
"Alive"
Upvotes: 2
Reputation: 6231
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.
Upvotes: 1