简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM