正则表达式:如何从标签内部获取内容(使用javascript)?

时间:2010-04-12 14:45:41

标签: javascript html regex

页面内容:

aa<b>1;2'3</b>hh<b>aaa</b>..
 .<b>bbb</b>
blabla..

我想得到结果:

1;2'3aaabbb

匹配代码为<b></b>

如何使用javascript编写此正则表达式? 谢谢!

5 个答案:

答案 0 :(得分:9)

Lazyanno

当且仅当

  1. 阅读SLaks的帖子(以及previous article he links to)和
  2. 您完全了解使用正则表达式从HTML中提取信息的众多奇妙方式
  3. 确信没有任何问题适用于您的情况(例如,您可以保证您的输入永远不会包含嵌套,不匹配等<b> / </b>标签或在<b>或评论</b>标记等中出现<script>...</script><!-- .. -->。)
  4. 绝对且肯定地希望继续进行正则表达式提取
  5. ...然后使用:

    var str = "aa<b>1;2'3</b>hh<b>aaa</b>..\n.<b>bbb</b>\nblabla..";
    
    var match, result = "", regex = /<b>(.*?)<\/b>/ig;
    while (match = regex.exec(str)) { result += match[1]; }
    
    alert(result);
    

    产地:

    1;2'3aaabbb
    

答案 1 :(得分:8)

You cannot parse HTML using regular expressions

相反,你应该使用Javascript的DOM。

例如(使用jQuery):

var text = "";
$('<div>' + htmlSource + '</div>')
    .find('b')
    .each(function() { text += $(this).text(); });

我将HTML包装在<div>标记中,以查找嵌套和非嵌套<b>元素。

答案 2 :(得分:2)

这是一个没有jQuery依赖的例子:

// get all elements with a certain tag name
var b = document.getElementsByTagName("B");

// map() executes a function on each array member and
// builds a new array from the function results...
var text = b.map( function(element) {
  // ...in this case we are interested in the element text
  if (typeof element.textContent != "undefined")
    return element.textContent; // standards compliant browsers
  else
    return element.innerText;   // IE
});

// now that we have an array of strings, we can join it
var result = text.join('');

答案 3 :(得分:2)

      var regex = /(<([^>]+)>)/ig;
      var bdy="aa<b>1;2'3</b>hh<b>aaa</b>..\n.<b>bbb</b>\nblabla..";

      var result =bdy.replace(regex, "");
      alert(result) ;

请参阅:http://jsfiddle.net/abdennour/gJ64g/

答案 4 :(得分:1)

只需使用'?'如果要使用常规表达式,则为内部文本生成模式后的字符。 例如:

".*" to "(.*?)"