Mizpah
Mizpah

Reputation: 13

javascript regex to match characters between two strings

I am entirely new to regex, and am trying to use it to match vales in order to map them to variables (javascript looking at the output in responceText generated from a php script).

At the moment I have this code:

if (xmlhttp.readyState==4)
  {
  document.getElementById("test").innerHTML=xmlhttp.responseText;
  cmake = xmlhttp.responseText.match(/Combined_Make =(.*?)</);
  }

Here is the (part) of the output its looking at:

echo "<span class=\"note\">";
echo "Test Output\n";
echo " Combined_Make = $model\n";
echo " Combined_Model = $marque\n";

when everything runs, its actually looking at a line like:

Combined_Make = GRAND JEEP CHEROKEE<br />

At the moment I am getting back precisely this:

'Combined_Make = GRAND JEEP CHEROKEE>, GRAND JEEP CHEROKEE'

Of course I am after just 'GRAND JEEP CHEROKEE' in this instance :) - I am also unsure why I am getting back that precise output!

Please note that I will need to assign multiple var$, each using a different start sting for the match!

Thanks in advance for any help!

Upvotes: 0

Views: 6664

Answers (2)

Peter Bailey
Peter Bailey

Reputation: 105914

String.match() always returns an array, even when there's only a single match (except when there's no match, then it returns NULL)

In the case of patterns that include captured subgroups, String.match() will always return the entire pattern match at index 0, and then subsequent matching groups at indexes 1 through N.

Here's a clear way to demonstrate that

"hello".match( /he(ll)(o)/ );
// yields ["hello", "ll", "o"]

Upvotes: 0

James
James

Reputation: 112000

Try:

/Combined_Make =([^<]+)/

And then you'll want to access the first capture group ([1]):

cmake = xmlhttp.responseText.match(/Combined_Make =([^<]+)/)[1];

You might want to test that it matches before trying to access the first capture group though:

var match = xmlhttp.responseText.match(/Combined_Make =([^<]+)/);
cmake = match && match[1];

Upvotes: 1

Related Questions