| To extract the title of an HTML page from a given HTML string using JavaScript, you can parse the HTML and retrieve the content of the <title> tag. Here's how to do it: The DOMParser in JavaScript is a web API used to parse an XML or HTML string into a DOM (Document Object Model) document. It enables developers to convert text-based markup (like HTML or XML) into an in-memory document object that can be navigated and manipulated using standard DOM methods. JavaScript Code to Get the Page Title:function getTitleFromHtml(html) {
// Create a DOM parser to parse the HTML string
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Retrieve the content of the <title> tag
const title = doc.querySelector('title');
// Return the text content of the title, or null if not found
return title ? title.textContent : null;
}
// Example HTML input (replace with your HTML content)
const htmlText = `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example Page Title</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
`;
// Extract the page title
const pageTitle = getTitleFromHtml(htmlText);
console.log(pageTitle); // Outputs: "Example Page Title"
Explanation:- DOMParser: Converts the HTML string into a DOM object.
- querySelector: Looks for the
<title> tag in the HTML. - textContent: Extracts the text content of the
<title> tag.
If the <title> tag is not found in the HTML, the function will return null. |