页面内容:
aa<b>1;2'3</b>hh<b>aaa</b>..
.<b>bbb</b>
blabla..
我想得到结果:
1;2'3aaabbb
匹配代码为<b>
和</b>
如何使用javascript编写此正则表达式? 谢谢!
答案 0 :(得分:9)
Lazyanno
,
当且仅当:
SLaks
的帖子(以及previous article he links to)和<b>
/ </b>
标签或在<b>
或评论</b>
标记等中出现<script>...</script>
或<!-- .. -->
。)...然后使用:
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) ;
答案 4 :(得分:1)
只需使用'?'如果要使用常规表达式,则为内部文本生成模式后的字符。 例如:
".*" to "(.*?)"