Mark Mark - 4 months ago 44
Javascript Question

Matching iframe src on index 1 in javascript

I need to match the url of an iframe src in the index 1. I am using this matchAll function to match multiple occurrences.

if (typeof RegExp.prototype.matchAll !== "function") {
RegExp.prototype.matchAll = function(v) {
var tmp = ""+ this, // So this.toString
src = tmp.lastIndexOf("/"),
pattern = tmp.substring(1, src),
flags = tmp.substring(src + 1, tmp.length);

// Never forget "g", that prepends infinite loops for "while"
if (flags.indexOf("g") == -1) {
flags += "g";

var re = new RegExp(pattern, flags);
var ms = [], m;
while (m = re.exec(v)) {
return ms;

Using this test code:

str = '<iframe width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>';
var pattern = /\[embed\](.*?)\[\/embed\]|<iframe.*?src="(.*?)".*?<\/iframe>/;
var matches = pattern.matchAll(str);

I do get the src, but on index 2, and I need it on index 1, because the pattern actually matches other things that uses the index 1 as the "url" so I rather match all the urls on that index instead of modifying the entire code.

Whats the correct pattern to get the src url on index 1 for any iframe?


To make both iframe url and embed url appear on index 1. Try the following code:

var pattern = /(?:(?:<iframe.*?src=")|(?:\[embed\]))(.*?)(?:\"|(?=\[\/embed\]))/;