Using JavaScript, how can I get the ad size width and height from a meta tag located in the HEAD section of my HTML file?
in HEAD of HTML file:
<script type="text/javascript">
// Returns a string "width=160,height=600"
var dimensionsStr = document.querySelector('meta[name="ad.size"]')['content'];
</script>
How can I parse this string to get:
var width = 160;
var height = 600;
You could extract all "variables" from that content dynamically like this:
// Returns a string "width=160,height=600"
var dimensionsStr = document.querySelector('meta[name="ad.size"]').content;
var obj = dimensionsStr.split(",").reduce( (obj, s) => {
var [key, value] = s.match(/[^\s;=]+/g);
obj[key] = isNaN(value) ? value : +value;
return obj;
}, {});
console.log(obj);
<meta name="ad.size" content="width=160,height=600"></meta>
This way it also doesn't matter if the order of width
and height
is reversed, or you have other variables in that content.