UNPKG

pyseoa-ts

Version:

SEO analysis tools for the web, ported from pyseoa (Python) to TypeScript

35 lines (34 loc) 1.09 kB
import * as cheerio from 'cheerio'; export function analyzeKeywordDensity(html, keyword, thresholds = { low: 0.5, high: 2 }) { const $ = cheerio.load(html); // extract visible body text $("script, style, noscript").remove(); const text = $("body").text(); const words = text .toLowerCase() .replace(/[^0-9a-z\s]/g, "") .split(/\s+/) .filter(Boolean); const normalizeKeyword = keyword.toLowerCase(); const count = words.filter(w => w === normalizeKeyword).length; const totalWords = words.length; const density = totalWords > 0 ? (count / totalWords) * 100 : 0; let score = 3; let message = "Keyword density is optimal."; if (density < thresholds.low) { score = 1; message = "Keyword density is too low."; } else if (density > thresholds.high) { score = 2; message = "Keyword density is too high."; } return { keyword: normalizeKeyword, count, totalWords, density: +density.toFixed(2), score, message, }; }