Categories
JavaScript Answers

How to replace words in the body text with JavaScript?

Spread the love

We can replace words in the body text of an HTML document using JavaScript by selecting the document.body element to access the entire body content, and then using the replace() method to replace occurrences of the words you want to replace.

To do this we write:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Replace Words in Body Text with JavaScript</title>
</head>
<body>

  <p>This is a paragraph containing some text.</p>

  <script>
    // Get the body element
    var body = document.body;

    // Get the text content of the body
    var bodyText = body.innerHTML;

    // Replace the word "paragraph" with "div" in the body text
    var newText = bodyText.replace(/paragraph/g, "div");

    // Update the body content with the new text
    body.innerHTML = newText;
  </script>

</body>
</html>

In this example, all occurrences of the word “paragraph” in the body text will be replaced with “div”. The replace() method is used with a regular expression (/paragraph/g) to replace all occurrences globally in the text.

Then, the updated text is assigned back to the innerHTML property of the body element, effectively replacing the original body text with the modified version.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *