user13460509
user13460509

Reputation:

Find <iframe> width and height

I have an object like this:

object = {
    iframe: "<iframe width="560" height="315" src="YouTube link"></iframe>"
}

I need to take the width (in this case 560) and height (in this case 315) value inside this with jQuery/js. Because I need to use this value.

Is that possible?

Thank you.

Upvotes: 1

Views: 126

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly note that the string in the example is invalid due to the repeated use of ". To make the string valid, delimit it with ' and use " to contain the attribute values within it.

As you've tagged the question with jQuery you can use that to build an object from the string instead of parsing it using regex:

let object = {
  iframe: '<iframe width="560" height="315" src="YouTube link"></iframe>'
}

let $iframe = $(object.iframe);

console.log($iframe.prop('width'));
console.log($iframe.prop('height'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Lemondoge
Lemondoge

Reputation: 989

You can use regex to isolate the two parameters:

var object = {
    iframe: '<iframe width="560" height="315" src="YouTube link"></iframe>' // string was invalid before, replaced quotes with apostrophes
}
var regexFound = object.iframe.match(/width="(\d*?)" height="(\d*?)"/);
var asArray = [regexFound[1], regexFound[2]];
var asObject = {width: regexFound[1], height: regexFound[2]}
console.log(asArray, asObject);

Upvotes: 1

Related Questions