How do I replace words in an HTML page using javascript?

I want to replace all words on a webpage that follow a set condition, with other words, which vary, depending on the word that is replaced. For example, let’s say I want to replace all words that are longer than 5 letters, with another word, also longer than 5 letters, which has the same first letter as the word that is to be replaced, and, is also longer than 5 letters. Now all the words in the page that are longer than 6 letters will be one of 26 possibilities.

This is what I tried, but it doesn’t work for more complex webpages. How do I solve this?

const segmenter = new Intl.Segmenter("en",{granularity:"word"});
const text = [...segmenter.segment(document.body.innerText)];
let test = "";
let alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
let replacements = "assignment behind controversial desperate eventually foundation growth happiness inside jurisdiction kingdom living million nightmare original president quantum revealed surprising travels understanding vacancies weather xenophobic yourself zombie Assignment Behind Controversial Desperate Eventually Foundation Growth Happiness Inside Jurisdiction Kingdom Living Million Nightmare Original President Quantum Revealed Surprising Travels Understanding Vacancies Weather Xenophobic Yourself Zombie".split(" ");
for (var word of text){
    test += ((word.segment.length<6)? word.segment:replacements[alphabets.indexOf(word.segment[0])])}
document.body.innerText=test;
console.log(test);