本文介绍了正则表达式匹配标签之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串:
My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.
我想在 b 标签到数组,即:
I'd like to get the text between
b
tags to an array, that is:
['Bob', '20', 'programming']
我试过这个
/< b>(。*?)< \ / b> /。exec(str)
但它只会获得第一个文本。
I tried this
/<b>(.*?)<\/b>/.exec(str)
but it will only get the first text.
推荐答案
/<b>(.*?)<\/b>/g
在以下后面添加
g
(全球)标志:
Add
g
(global) flag after:
/<b>(.*?)<\/b>/g.exec(str)
//^-----here it is
但是如果你想获得所有匹配的元素,那么你需要这样的东西:
However if you want to get all matched elements, then you need something like this:
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"]
这篇关于正则表达式匹配标签之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!