javascriptjqueryregexhtml-meta

using javascript regex, get meta tags data from a web page


I wanna get meta tags data using javascript(jquery) and regex.

Here are some meta tags.

<meta name="description" content="Amazon.com : Google Chromecast HDMI Streaming Media Player : Streaming Media Clients : Electronics" />
<meta name="title" content="Amazon.com : Google Chromecast HDMI Streaming Media Player : Streaming Media Clients : Electronics" />

I can get content from those forms using below function.

function getProductInfo(attr) {
    var m = $("meta[name="+attr+"]");
    var content = m.attr("content");
    return content; 
}
if(!title) var title = getProductInfo('title');

However sometimes there are different form of meta tags like

<meta property="title" content="....">
<meta property="og:title" content="....">
<meta name="title" description="....">

That's why I'm considering using regex. but I have no idea. please give me a tip. thanks.


Solution

  • Here's how you do it by not using RegEx

    No libraries, pure vanilla JS:

    var meta = document.querySelectorAll('meta');
    for(var i=0;i<meta.length;i++){
       var content = meta[i].getAttribute('content'); /* here's the content */
    }
    

    http://jsfiddle.net/JA9Yq/

    jQuery:

    $('meta').each(function(index,tag){
        var content = tag.getAttribute('content');
    });
    

    http://jsfiddle.net/duL6E/