| Keywords are important because they help convey the subject and purpose of content to both users and search engines. In the context of web development and SEO (Search Engine Optimization), keywords serve several critical roles, including improving discoverability, relevance, and targeting. However, their importance has evolved over time, especially with the changes in how search engines rank content. To extract the keywords from an HTML page using JavaScript, you need to target the <meta name="keywords"> tag in the document. Here's how to retrieve the value of the content attribute of this meta tag: JavaScript Code to Get Page Keywords:function getPageKeywordsFromHtml(html) {
// Create a DOM parser to parse the HTML string
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Look for the meta tag with name="keywords"
const keywordsMeta = doc.querySelector('meta[name="keywords"]');
// Return the content attribute of the meta tag, or null if not found
return keywordsMeta ? keywordsMeta.getAttribute('content') : null;
}
// Example HTML input (replace with your HTML content)
const htmlText = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="keywords" content="HTML, JavaScript, CSS, Web Development">
<title>Example Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
`;
// Extract the page keywords
const pageKeywords = getPageKeywordsFromHtml(htmlText);
console.log(pageKeywords); // Outputs: "HTML, JavaScript, CSS, Web Development"
Explanation:- DOMParser: Converts the HTML string into a DOM object.
meta[name="keywords"]: Searches for the meta tag with the name="keywords" attribute.getAttribute('content'): Retrieves the content of the keywords meta tag, which typically contains a comma-separated list of keywords relevant to the page.
Output:If the meta keywords tag is found, the function returns the keywords as a string. If not, it returns null. Example Use Case:If the page has a meta keywords tag like this: html 코드 복사 <meta name="keywords" content="HTML, JavaScript, CSS, Web Development">
The output will be: arduino 코드 복사 "HTML, JavaScript, CSS, Web Development"
|