inspiringmyself
inspiringmyself

Reputation: 590

Regular expression to extract text from a string in html format

I am currently getting response error in html format. It is of type string.

"<!DOCTYPE html>\r\n
<html>
  <head>
    <title>Data already exists</title>
  </head>
</html>"

I wanted to retrieve the content inside the <title>, for above instance "Data already exists". Can anybody suggest a appropriate regular expression to capture that text.

Please any help is appreciated!

Upvotes: 3

Views: 4308

Answers (3)

elclanrs
elclanrs

Reputation: 94131

The very basics of parsing html tags in regex is this. http://jsbin.com/oqivup/1/edit

var text = /<(title)>(.+)<\/\1>/.exec(html).pop();

But for more complicated stuff I would consider using a proper parser.

Upvotes: 2

Oriol
Oriol

Reputation: 288680

You could parse it using DOMParser():

var parser=new DOMParser(),
    doc=parser.parseFromString("<!DOCTYPE html><html><head><title>Data already exists</title></head></html>","text/html");

doc.title; /* "Data already exists" */

Upvotes: 1

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91349

First, you can do it without regex, by creating a dummy element to inject the HTML:

var s = "your_html_string";
var dummy = document.createElement("div");
dummy.innerHTML = s;
var title = dummy.getElementsByTagName("title")[0].innerText;

But if you really insist on using regex:

var s = "your_html_string";
var title = s.match(/<title>([^<]+)<\/title>/)[1];

Here's a DEMO illustrating both approaches.

Upvotes: 5

Related Questions