I'm almost there! Just can't figure out the last part of what I need... forming the array.
I want to go through an html file and extract url's from between the phrases playVideo(' and ')
For testing purposes I am just trying to get it to work on the variable str, eventually this will be replaced by the html document:
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match("playVideo\\(\'(.*?)\'");
alert(testRE[1]);
</script>
This will output 'url1' but if I change it to alert(testRE[2]) it is undefined. How can I get it to fill out the array with all of the URLs (eg testRE[2] output 'url2' and so on) ?
Thanks for any help, new to regex.
-
stackoverflow.com/questions/6825492/…user785262– user7852622012年01月31日 00:48:57 +00:00Commented Jan 31, 2012 at 0:48
-
Thanks for the link Ben but I don't see how that applies. I won't know what string I'm looking for since they will all eventually be various urls, so how could I indexOf for an unknown string?dougmacklin– dougmacklin2012年01月31日 00:59:42 +00:00Commented Jan 31, 2012 at 0:59
-
Read the page--you look for that playVideo part of the string, it places you right at the start of each url you are looking for in succession.user785262– user7852622012年01月31日 05:06:26 +00:00Commented Jan 31, 2012 at 5:06
2 Answers 2
Cannot comment, why is that, but adding that by iterating on the regex you get access to the groups;
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var re = /playVideo\('(.*?)'\)/g;
while (match = re.exec(str)) {
alert(match[1]);
}
1 Comment
Normally a javascript regular expression will just perform the first match. Update your regular expression to add the g modifier. Unfortunately JavaScript regular expressions don't have a non-capturing group so you have to do a little more processing to extract the bit you want e.g.
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match(/playVideo\(\'[^']*\'/g);
var urls = [];
for (var i = 0; i < testRE.length; i++)
{
urls[i] = testRE[i].substring(11).match(/[^']*/);
}
alert(urls[1]);
alert(urls[2]);
</script>