3

I want to extract from an html tag string name only. I would like to obtain this result:

  • Farm 1
  • STAGING
  • STAGING_SYSTEM_10

what type regular expression can I use?

<div class='singleNode'><i class='fa fa-cogs'></i><span>Farm 1<span class='badge badge-primary'></span><span></div>

 <div class='singleNode'><i class='fa fa-cubes'></i><span>STAGING<span class='badge badge-primary'></span><span></div>

<div class='singleNode'><i class='fa fa-desktop'></i><span>STAGING_SYSTEM_10<span class='badge badge-primary'></span><span></div>
user3790694
  • 353
  • 2
  • 3
  • 15
  • 3
    Use an HTML parser and not a regex. The effects of a regex with HTML can be [unfortunate](http://stackoverflow.com/a/1732454/67392). – Richard Apr 01 '15 at 08:29

1 Answers1

5

In case you have to use regex, here is the sample code:

var re = /<div[^>]*?>(?:<(\S+)[^>]*?>[^<]*?<\/\1>)+<span[^]*?>([^<]*?)(?=<span )/g; 
var str = '<div class=\'singleNode\'><i class=\'fa fa-cogs\'></i><span>Farm 1<span class=\'badge badge-primary\'></span><span></div>\n\n <div class=\'singleNode\'><i class=\'fa fa-cubes\'></i><span>STAGING<span class=\'badge badge-primary\'></span><span></div>\n\n<div class=\'singleNode\'><i class=\'fa fa-desktop\'></i><span>STAGING_SYSTEM_10<span class=\'badge badge-primary\'></span><span></div>';
var m;
 
while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // m[2] is the 2nd capture group, the text inside the DIV element
    alert(m[2])
}

In case you can parse it with DOM, use this code:

var input = document.getElementsByTagName("div");
for ($i = 0; $i < input.length; $i++)
{
   alert(input[$i].textContent);
}
<body>
<div class='singleNode'><i class='fa fa-cogs'></i><span>Farm 1<span class='badge badge-primary'></span><span></div>

 <div class='singleNode'><i class='fa fa-cubes'></i><span>STAGING<span class='badge badge-primary'></span><span></div>

<div class='singleNode'><i class='fa fa-desktop'></i><span>STAGING_SYSTEM_10<span class='badge badge-primary'></span><span></div>
  </body>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563