简体   繁体   English

使用javascript解析html字符串

[英]parse html string using javascript

I want to extract part of html string which format is given as below. 我想提取部分HTML字符串,其格式如下。 This html string is returned by var contents = $("#content").html() 此html字符串由var contents = $("#content").html()

blah1 blah1
<p> blah2 blah2 </p>

Then I use 然后我用

start = contents.indexOf("<p>");
end = contents.indexOf("</p>");

to get the start and end positions. 获取开始和结束位置。 So I can use contents.slice(start, end) to extract the string I want. 所以我可以使用contents.slice(开始,结束)来提取我想要的字符串。

But in IE browser the <p> tag is capital <P> and in Chrome and Firefox, they user <p> 但是在IE浏览器中, <p>标记是大写的<P>而在Chrome和Firefox中,它们的用户是<p>

How can I include both cases so that my JavaScript function can work in all browsers? 如何包含这两种情况,以便我的JavaScript函数可以在所有浏览器中使用? Thanks 谢谢

您可以使用:

$('#content p').text();

Why not just grab the innerHTML of the p tag in question? 为什么不仅仅抓住有问题的p标签的innerHTML?

jQuery: jQuery的:

var contents = $("#content > p").html();

or even, just the plain text: 甚至只是纯文本:

var contents = $("#content > p").text();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM