TheCarver
TheCarver

Reputation: 19713

jQuery - Get part of a string

In JS/jQuery, I need to strip a YouTube embed code to reveal just the SRC value. How is this possible?

The embed code, for example:

string = "<iframe width="630" height="354" src="https://www.youtube.com/embed/NYjPglsyYZA?rel=0" frameborder="0" allowfullscreen></iframe>"

I am looking to grab everything between src=" and ". I'm thinking maybe a regular expression will do it but not overly sure...

Any suggestions would be great.

Upvotes: 0

Views: 680

Answers (3)

artlung
artlung

Reputation: 34013

In jQuery:

$('iframe:first').attr('src');

In plain JavaScript:

document.getElementsByTagName('iframe')[0].src;

UPDATE

Starting with a string, using jQuery:

string = '<iframe width="630" height="354" src="https://www.youtube.com/embed/NYjPglsyYZA?rel=0" frameborder="0" allowfullscreen></iframe>';
var src = $(string).attr('src');

And without jQuery:

string = '<iframe width="630" height="354" src="https://www.youtube.com/embed/NYjPglsyYZA?rel=0" frameborder="0" allowfullscreen></iframe>';
var div = document.createElement('div');
div.innerHTML = string;
var src = div.firstChild.src;

alert(src);

Upvotes: 2

mgraph
mgraph

Reputation: 15338

try :

var str='<iframe width="630" height="354" src="https://www.youtube.com/embed/NYjPglsyYZA?rel=0" frameborder="0" allowfullscreen></iframe>'; 
var src = $(str).attr("src");

Upvotes: 4

ZnArK
ZnArK

Reputation: 1541

http://www.w3schools.com/jsref/jsref_match.asp

Try this

var str='<iframe width="630" height="354" src="https://www.youtube.com/embed/NYjPglsyYZA?rel=0" frameborder="0" allowfullscreen></iframe>'; 
var n=str.match(/src="(.*)"/);
var result = n.substring(5,n.length()-1);

Upvotes: -1

Related Questions