-2

I am building an application which needs to select specific text between html, here is an example:

String: <p><a href="test0">test1 test2</a>test3</p>

RegExp: (Select text between HTML)(test.)

What I want to select is "test1","test2" and "test3" but not "test0"

Is there any solution??Thanks for any helps

Note: I am using JavaScript for RegExp operation.

4

2 回答 2

3

您可以利用浏览器为您解析 HTML 的能力:

var html = '<p><a href="test0">test1 test2</a>test3</p>',
fragment = document.createDocumentFragment(),
div = fragment.appendChild(document.createElement('div'));

div.innerHTML = html;

console.log(div.textContent || div.innerText || '');

输出:

test1 test2test3
于 2013-04-02T06:35:34.563 回答
1

我不会将正则表达式用于此类任务,如果您只需要<p>标签文本,我会使用 jQuery:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <p><a href="test0">test1 test2</a>test3</p>
  <script>
  $(function(){
    text = $('p').text();
    alert(text);
  });
  </script>
</body>
</html>

这返回test1 test2test3

工作示例:http: //jsbin.com/uhadoz/1/

如果您想要更通用的解决方案,您仍然可以使用 jquery,只需更改选择器:例如,要获取 all 的文本divs,请使用$('div').text()

但是如果你有严重的解析需求,你最好使用 HTML 解析器,google for JavaScript HTML 解析器,例如这个:http ://ejohn.org/blog/pure-javascript-html-parser/

阅读这个关于使用正则表达式解析 HTML 的 SO 问题:RegEx match open tags except XHTML self-contained tags

于 2013-04-02T06:21:21.500 回答