Mark Mark - 11 days ago 6
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)) {
ms.push(m);
}
return ms;
};
}


Using this test code:

str = '<iframe width="560" height="315" src="https://www.youtube.com/embed/8L-6Hw7CZLQ" frameborder="0" allowfullscreen></iframe>';
var pattern = /\[embed\](.*?)\[\/embed\]|<iframe.*?src="(.*?)".*?<\/iframe>/;
var matches = pattern.matchAll(str);
console.log(matches);


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?

Answer

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

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