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.
$('meta').each(function() {
console.log($(this).attr('content'));
});
No need for regex, for unsorted tags.
function getProductInfo(attr) {
$('meta').each(function(index,tag) {
if($(tag)[0].attributes[0].textContent == attr) {
console.log($(tag)[0].attributes[0].textContent, $(tag)[0].attributes[1].textContent);
}
});
}
getProductInfo('title');
This will get you anything , that has title in name/property.
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 */
}
jQuery:
$('meta').each(function(index,tag){
var content = tag.getAttribute('content');
});
Its also possible using RegEx:
<meta[^>]+content="([^")]*)"
Result:
$matches Array:
(
[0] => Array
(
[0] => <meta name="description" content="Amazon.com : Google Chromecast HDMI Streaming Media Player : Streaming Media Clients : Electronics"
[1] => <meta name="title" content="Amazon.com : Google Chromecast HDMI Streaming Media Player : Streaming Media Clients : Electronics"
)
[1] => Array
(
[0] => Amazon.com : Google Chromecast HDMI Streaming Media Player : Streaming Media Clients : Electronics
[1] => Amazon.com : Google Chromecast HDMI Streaming Media Player : Streaming Media Clients : Electronics
)
)
may be this..
var desc = $('meta[name=description]').attr("content");
var title= $('meta[name=title]').attr("content");
var desc = $('meta[property=description]').attr("content");
var title= $("meta[property='og:title]").attr("content");
note: Apparently it doesn't like the colon. I was able to fix it by using double and single quotes like this:
This should work on all meta tags I think...
/\<meta.*?\>/
Here's a link to regexr, which is a good tool to try things out
But it's better to use @subZero advice and not use regex if you don't have to... I think.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.