Search code examples
javascripthtmlhtml-parsingmeta-tags

Parse ad.size meta tag to parse width / height into integers with JavaScript Regex


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;

Solution

  • 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.