Regex match text between tags

JavascriptRegex

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

/<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)

Solution 2 - Javascript

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

Solution 3 - Javascript

Use match instead, and the g flag.

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

Solution 4 - Javascript

Try

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionwong2View Question on Stackoverflow
Solution 1 - JavascriptEngineerView Answer on Stackoverflow
Solution 2 - JavascriptEsailijaView Answer on Stackoverflow
Solution 3 - JavascriptBali BaloView Answer on Stackoverflow
Solution 4 - JavascriptxdazzView Answer on Stackoverflow