如何从JavaScript中的HTML字符串中提取div中的所有内容

我有一个像这样的HTML字符串: –

var html = ''; 

如何提取

所有内容?

在jQuery中你可以做$($html).html();

在php中你可以使用像Simple HTML DOM这样的东西

看看DOM或其​​他PHP XML库。

http://se.php.net/manual/en/book.dom.php

String是一个字符串。 使用正则表达式来解析它。

在JS方面:
看看替换或匹配
像(未测试)的东西:

 pattern = '/
(.*?)<\/div>/'; matches = html.match(pattern); result= matches[1];

这可能不起作用,因为它将在第一个停止,但正则表达式是这里的方式,只需找到一个返回所需内容的表达式。

一般来说,我认为在PHP或JS变量中“硬编码”HTML是一个坏主意。
恕我直言,最好使用模板引擎,它可以像Mustache一样在双方(客户端和服务器)上使用。 它提供HTML与任何类型的应用程序逻辑,客户端(JS)或服务器(PHP)的完全分离。

好吧,我前段时间遇到了同样的问题,而且它与从ajax结果中刷新一个div会产生同样的页面html,但现在我只想抓住我想要的id,然后设置innerHTML。 所以我写了一个javascript函数来做到这一点,

  //Extracts all the string or html content from a named div function ExtractFromDiv(str_html, str_div_id) { //The string we want to return at the end var str_return = ""; //We would copy all the string contents inside a div
var str_div_contents = ""; //We need to know where to start the search var start_index = -1; //We want to store the length of the string var int_str_len = 0; //The array for the beginning of a div var arr_div_start = new Array('<', 'd', 'i', 'v', ' '); //The array that ends a div var arr_div_end = new Array('<', '/', 'd', 'i', 'v', '>'); //The ending character var char_end = '>'; //We must put this in the notation '' str_div_id = '\'' + str_div_id + '\''; //Lets iterate for all the characters but we start from the first div start_index = str_html.indexOf(" if ( boo_div_start ) { str_div_contents = str_div_contents + char_current; } else { str_div_contents = ""; } //Now we must detect the end of the div if we had detected the start before if ( boo_div_start ) { //The end of the div is denoted by a > if( char_current == '>' ) { //We have just copied whats in a div then we must check the id we wanted if ( boo_div_with_id == false ) { boo_div_with_id = ( str_div_contents.indexOf(str_div_id) != -1); // We set this to 1, if we get a new div we increment it by 1 if we get to the end of a div we decrease it by 1 int_opened_div_count = 1; } str_div_contents = ""; boo_div_start = false; } } } return str_return; } //U can try this function as follows in your code

///它适用于我的目的。 好编码!

Interesting Posts