Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  170] [ 4]  / answers: 1 / hits: 144396  / 12 Years ago, sat, july 21, 2012, 12:00:00

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.


More From » regex

 Answers
111
/<b>(.*?)</b>/g


Regular



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)

[#84109] Thursday, July 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
valentinam

Total Points: 166
Total Questions: 117
Total Answers: 81

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
;