我有这个字符串:正则表达式匹配文本
My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.
我想b
标签之间的文本到一个数组,那就是:
['Bob', '20', 'programming']
我想这/<b>(.*?)<\/b>/.exec(str)
但它只会得到第一个文本。
我有这个字符串:正则表达式匹配文本
My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.
我想b
标签之间的文本到一个数组,那就是:
['Bob', '20', 'programming']
我想这/<b>(.*?)<\/b>/.exec(str)
但它只会得到第一个文本。
/<b>(.*?)<\/b>/g
添加g
(全球)标志后:
/<b>(.*?)<\/b>/g.exec(str)
//^-----here it is
但是,如果你想获得的所有匹配的元素,那么你就需要这样的事:
var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"]
但结果是'[“Bob”,“Bob”]'? – wong2 2012-07-21 12:10:51
_exec_应该多次使用,因为它记住了最后的调用结果并返回下一个调用结果。 – 2012-07-21 12:13:41
@ wong2这个标签被replace()去掉了, – 2013-09-18 21:15:46
使用改为,而g标志。
str.match(/<b>(.*?)<\/b>/g);
var root = document.createElement("div");
root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var texts = [].map.call(root.querySelectorAll("b"), function(v){
return v.textContent || v.innerText || "";
});
//["Bob", "20", "programming"]
尝试
str.match(/<b>(.*?)<\/b>/g);
使用DOM接口。更轻松。 – 2012-07-21 12:10:32
@EdHeal此HTML字符串不在DOM中 – wong2 2012-07-21 12:11:45
您需要了解的有关使用正则表达式解析HTML的所有内容:[* RegEx匹配除XHTML自包含标记以外的开放标记](http://stackoverflow.com/questions/1732348 /正则表达式匹配开放标签,除了-XHTML-自足标签/ 1732454#1732454)。 – RobG 2015-09-07 10:02:32