Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match text between tags [duplicate]

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 b tags to an array, that is:

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

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

like image 516
wong2 Avatar asked Jul 21 '12 12:07

wong2


3 Answers

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

Regular expression visualization

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

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)
like image 159
Engineer Avatar answered Nov 10 '22 21:11

Engineer


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"]
like image 14
Esailija Avatar answered Nov 10 '22 21:11

Esailija


Use match instead, and the g flag.

str.match(/<b>(.*?)<\/b>/g);
like image 12
Bali Balo Avatar answered Nov 10 '22 22:11

Bali Balo