admin管理员组文章数量:1396787
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!
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!
Share Improve this question asked Aug 29, 2012 at 1:17 inspiringmyselfinspiringmyself 5901 gold badge11 silver badges29 bronze badges 1- I really appreciate everyone's suggestion and thanks for taking time to share the knowledge. You guys are awesome. – inspiringmyself Commented Aug 29, 2012 at 14:07
3 Answers
Reset to default 5First, 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.
The very basics of parsing html tags in regex is this. http://jsbin./oqivup/1/edit
var text = /<(title)>(.+)<\/\1>/.exec(html).pop();
But for more plicated stuff I would consider using a proper parser.
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" */
本文标签: javascriptRegular expression to extract text from a string in html formatStack Overflow
版权声明:本文标题:javascript - Regular expression to extract text from a string in html format - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744128836a2592080.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论