Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12231

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

$
0
0

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.

I tried to accomplish this by taking all of the HTML and replacing all words that were longer than 5 letters and outside a tag, but my code changes the hyperlink, and adds my JS script to the html page. Why does this happen? How do I accomplish what I want to?

const segmenter = new Intl.Segmenter("en",{granularity:"word"});const text = [...segmenter.segment(document.body.innerHTML)];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("");let intag = false;for (var word of text){if((word.segment=="<"||word.segment==">")&&!intag){  intag=!intag}  test += ((word.segment.length<6)? word.segment:replacements[alphabets.indexOf(word.segment[0])])}document.body.innerHTML=test;console.log(test);
<h1> Replacing words in a webpage </h1><a href="https://stackoverflow.com/posts/78633403">Why won't this work?</a>

Viewing all articles
Browse latest Browse all 12231

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>