Files
tp-javascript-introduction/partie2-seo.js
2025-07-12 11:10:38 +02:00

52 lines
1.4 KiB
JavaScript

let text = "";
let keyword = "";
const button = document.getElementById('analyse');
function wordFrequency(texte, keyword) {
const occurrencies = [];
const words = text.trim().split(/[^a-zA-Z]/);
words.forEach(word => {
if (word === keyword) {
occurrencies.push(word);
}
});
return occurrencies.length;
}
function infosHTML(htmlText) {
const infos = {};
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlText, "text/html");
infos.title = newDoc.getElementsByTagName("title")[0].textContent;
infos.description = newDoc.querySelector("meta[name='description']").content;
return infos;
}
button.addEventListener('click', (e) => {
e.preventDefault();
text = document.getElementById('zone-html').value;
keyword = document.getElementById('keyword').value;
const pageTitle = document.getElementById('page-title');
const pageDescription = document.getElementById('page-meta-description');
pageTitle.style.fontWeight = "normal";
pageTitle.innerText = infosHTML(text).title;
pageDescription.style.fontWeight = "normal";
pageDescription.innerText = infosHTML(text).description;
const keywordNumber = document.getElementById('keyword-number');
keywordNumber.innerText = `Nombre d'occurrences de "${keyword}" : ${wordFrequency(text, keyword)}`;
});