如何使用JavaScript从带有HTML的字符串中删除整个HTML、HEAD标记和BODY标记

How to remove whole HTML, HEAD tags and BODY tag from string with HTML using JavaScript?

本文关键字:HTML HEAD 标记 BODY JavaScript 何使用 字符串 删除      更新时间:2023-09-26

我有一个名为myWebsite.html的模板文件。它包含html模板需要的所有内容。所以它有HTML、HEAD和BODY标记。我想用JavaScript加载它,并将其放入网站上的一个div中。所以我不想有HTML、HEAD和BODY标签。如何做到这一点?

这是我需要的一个原型:

$val = getData('myWebsite.html');
$val = removeHTMLHEADBODYTAGS($val); //remove these tags with everything insite, also remove the body tag but leave the contents in the body tag. Also remove the end tags of body and html - HOW TO DO THIS?
div.innerHTML = $val;

我想在纯JavaScript=NO jQUERY

中执行此操作

为什么不从标记中提取信息,然后使用它呢?没有必要获取所有信息并删除html、头和正文:

content = $val.getElementsByTagName('body')[0].innerHTML();

您可以使用正则表达式提取它。类似于:/'<body[^>]*'>(.*)'<'/body/m-应该返回<BODY>元素中的所有内容。

$val = getData('myWebsite.html');
var reg = /'<body[^>]*'>([^]*)'<'/body/m;
div.innerHTML = $val.match( reg )[1];

示例jsFiddle代码:http://jsfiddle.net/x4hPZ/1/

使用jQuery,您可以这样做:

$(document).ready(function(){
    var your_content = $("html").clone().find("head,body").remove().end().html();
});
  1. 使用"html"选择器获取内容
  2. clone复制
  3. find要删除的标记
  4. 移除它们并
  5. 转换回HTML

所有这些都在一条线上。

HTH,

--hennson

怎么样:

var bodyContents = htmlstring.split('<body');//no >, body could have a property
bodyContents = bodyContents[1].replace('</body>','').replace('</html>','').replace(/^.*'>/,'');

最后一个regex-replace删除了开头body标记的结束>,以及所有可能的标记属性。

然而,这不是我做事的方式。。。如果可能的话,我会创建一个(I)Frame节点,将html加载到该框架中,并从body标记中获取innerHTML。只是一个建议。

对,iFrame方式:

var document.ifrm = document.createElement('iframe')
document.ifrm.style = 'visibility:hidden';
document.body.appendChild(document.ifrm);
idoc = (document.ifrm.contentDocument ? document.ifrm.contentDocument : document.ifrm.contentWindow.document;)
idoc.open();
idoc.writeln('<html><head><title>foobar</title></head><body><p>Content</p></body></html>');
idoc.close();
var bodyContents = idoc.body.innerHTML;

代码说明:http://softwareas.com/injecting-html-into-an-iframe

或谷歌网站上的任何其他点击:)