james
james

Reputation:

Javascript RegEx: Get all text matches surrounded by some other text?

In JavaScript/JQuery I want to get all the text that is seen between some other text. For example, if the HTML document had:

<b class="blah">Blah: Some Text 1</b>
<div id="foo"><b class="blah">Blah: Some Text 2</b>

I'd like to get an array that has 'Some Text 1' and 'Some Text 2' since they are both in between '<b class="blah">Blah:' followed by a '</b>'

Upvotes: 2

Views: 3231

Answers (3)

port-zero
port-zero

Reputation: 667

This code will produce an array with the text between '<b class="blah">Blah:' and '</b>'. in this example 'Some Text 1' and 'Some Text 2'

var s = '<b class="blah">Blah: Some Text 1</b><div id="foo"><b class="blah">Blah: Some Text 2</b>';

var regex = /<b class="blah">Blah: (.+?)<\/b>/gi;
var result = [];
var e;
while (e = regex.exec(s))
{
  result.push(e[1]);
};

Upvotes: 0

Peter Bailey
Peter Bailey

Reputation: 105914

Since you mention jQuery, just select all the right nodes and check their text. You can put a regex in here if you want, but it's not needed.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$( function(){
    var texts = [];
    $('b.blah').each( function()
    {
      var txt = $(this).text();
      if ( 0 == txt.indexOf( 'Blah:' ) )
      {
          texts.push( txt.substr( 6 ) );
      }
    } );
    alert( texts );
});
</script>

</head>
<body>
  <b class="blah">Blah: Some Text 1</b>
  <div id="foo"><b class="blah">Blah: Some Text 2</b>
  <div id="foo"><b class="blah">Some Text 3</b>
</body>
</html>

Or with a string of HTML

$( function(){
  var htmlChunk = '<b class="blah">Blah: Some Text 1</b>\n'
    + '<div id="foo"><b class="blah">Blah: Some Text 2</b></div>\n'
    + '<div id="foo2"><b class="blah">Some Text 3</b></div>';

    var texts = [];
    $('b.blah', '<div>' + htmlChunk + '</div>').each( function()
    {
      var txt = $(this).text();
      if ( 0 == txt.indexOf( 'Blah:' ) )
      {
          texts.push( txt.substr( 6 ) );
      }
    } );
    alert( texts );
});

Upvotes: 1

chaos
chaos

Reputation: 124365

This is kind of hard in JS, because there's no handy way to retrieve a global set of paren captures. A hack like this might work:

var chunked = text.replace(/.*<b class="blah">(.*?)<\/b>/g, '$1|ARBITRARY_SEPARATOR|');
var chunks = chunked.split(/|ARBITRARY_SEPARATOR|/);
chunks.pop();

Upvotes: 0

Related Questions