Javascript 正则表达式匹配标签之间的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11592033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:27:43  来源:igfitidea点击:

Regex match text between tags

javascriptregex

提问by wong2

I have this string:

我有这个字符串:

My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.

I'd like to get the text between btags to an array, that is:

我想将b标签之间的文本放到一个数组中,即:

['Bob', '20', 'programming']

I tried this /<b>(.*?)<\/b>/.exec(str)but it will only get the first text.

我试过这个,/<b>(.*?)<\/b>/.exec(str)但它只会得到第一个文本。

回答by Engineer

/<b>(.*?)<\/b>/g

Regular expression visualization

正则表达式可视化

Add g(global) flag after:

在以下位置添加g( global) 标志:

/<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"] 

If an element has attributes, regexp will be:

如果元素具有属性,则 regexp 将是:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

回答by Esailija

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"]

回答by Bali Balo

Use matchinstead, and the g flag.

使用match和 g 标志。

str.match(/<b>(.*?)<\/b>/g);

回答by xdazz

Try

尝试

str.match(/<b>(.*?)<\/b>/g);