Build a Find and Replace Tool using HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to craft a powerful find and replace tool using HTML, CSS, and JavaScript. Master text manipulation in this step-by-step guide.


Build a Find and Replace Tool using HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Text manipulation is a fundamental aspect of digital communication and content creation. Whether you're editing a document, updating code snippets, or refining website content, the ability to find and replace specific words or phrases is a powerful tool that can save time and ensure accuracy. In this comprehensive tutorial, we will walk you through the step-by-step process of creating your very own find and replace tool using HTML, CSS, and JavaScript.

Imagine a scenario where you have a lengthy document filled with repetitive terms that need to be updated. Manually scanning through the document and making changes one by one can be a daunting and error-prone task. This is where a find and replace tool comes to the rescue. With a custom-made tool at your disposal, you can effortlessly locate all instances of a particular word or phrase and replace them with the desired text, instantly transforming your content.

The beauty of this tutorial lies in its simplicity and practicality. We will guide you through the creation of a user-friendly web-based find and replace tool that requires no installation or specialized software. By harnessing the power of HTML, CSS, and JavaScript, you will gain a deeper understanding of how these three technologies collaborate to deliver a seamless user experience.

As you embark on this journey, you don't need to be an expert programmer or a seasoned web developer. Our instructions are designed to be beginner-friendly, allowing you to grasp the core concepts and gradually build your skills. Along the way, you'll learn about HTML's role in structuring the tool's interface, CSS's ability to enhance its visual appeal, and JavaScript's magic in handling the intricate find and replace logic.

By the end of this tutorial, you'll have a fully functional find and replace tool that you can proudly incorporate into your workflow. Not only will you have a valuable asset for your own text manipulation tasks, but you'll also have a deeper appreciation for the synergy between HTML, CSS, and JavaScript in the realm of web development.

So, whether you're a content creator, a programmer, or someone eager to expand your skill set, join us as we dive into the world of find and replace tools. Get ready to empower yourself with the knowledge and tools to conquer text manipulation challenges and enhance your efficiency in the digital realm. Let's begin the journey of crafting your very own find and replace tool using HTML, CSS, and JavaScript.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our find and replace tool.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down the code step by step:

1. <!DOCTYPE html>: This is a declaration that specifies the document type and version of HTML being used, which in this case is HTML5.

2. <html lang="en">: This is the opening tag for the HTML document. The lang attribute indicates that the language of the content is English.

3. <head>: This section contains meta-information and external resources used by the web page.

  • <meta charset="UTF-8">: Specifies the character encoding for the document, which is UTF-8 (a widely used character encoding for handling various languages).
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport properties for responsive design, ensuring the page displays properly on various devices and screen sizes.
  • <title>Find and Replace Tool</title>: Sets the title of the web page, which is displayed in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css">: Links an external CSS stylesheet (styles.css) to the HTML document for styling the page's appearance.

4. <body>: This section contains the visible content of the web page that users see in their browsers.

  • <div class="container">: A container element that wraps the entire content of the web page. It is often used for layout and styling purposes.
  • <h1>Find and Replace Tool</h1>: A level 1 heading that displays the main title of the web page.
  • <div class="form-container">: A container for the form elements of the "Find and Replace" tool.
  • <label for="inputText">Input Text:</label>: A label for the text area below, indicating its purpose.
  • <textarea id="inputText" placeholder="Enter your text here"></textarea>: A multi-line input field where users can enter the text they want to perform find and replace operations on.
  • <div class="input-group">: A container for the find and replace input fields and button.
  • <input type="text" id="findInput" placeholder="Find">: A single-line input field where users can specify the text they want to find.
  • <input type="text" id="replaceInput" placeholder="Replace with">: A single-line input field where users can specify the replacement text.
  • <button id="replaceButton">Replace</button>: A button that users can click to initiate the find and replace operation.
  • <div class="count" id="countDisplay"></div>: An empty container that will be used to display the count of replaced occurrences.

5. </body>: The closing tag for the <body> section.

6. </html>: The closing tag for the HTML document.

This is the basic structure of our find and replace tool using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Next, we'll create a style sheet for our HTML page. This style sheet will govern how all the elements on our website look. We'll use some simple styles to make our HTML page look nice and consistent.

Let's break down the code step by step:

1. The body selector applies styles to the entire webpage's body element. Here are the styles applied:

  • font-family: The chosen font for text content, with a fallback to Arial and other sans-serif fonts.
  • margin and padding: Sets margin and padding to 0 for the body element, removing any default spacing.
  • background-color: Sets the background color of the body to a light gray.

2. The .container class selector applies styles to a container element, presumably used to wrap content on the webpage. Here are the styles applied:

  • max-width: Limits the width of the container to a maximum of 800 pixels.
  • margin: Centers the container horizontally with a 10-pixel margin at the top and bottom.
  • padding: Adds 20 pixels of padding inside the container.
  • background-color: Sets the background color of the container to white.
  • box-shadow: Adds a subtle shadow around the container for a raised appearance.
  • border-radius: Rounds the corners of the container by 5 pixels.

3. The h1 selector applies styles to all h1 headings on the webpage:

  • font-size: Sets the font size to 24 pixels.
  • margin-bottom: Adds a 20-pixel margin at the bottom of h1 headings.
  • color: Sets the text color to a dark gray (#333).

4. The .form-container class selector applies styles to a form container element, presumably for containing form fields. It applies a flex layout with a column direction.

5. The label selector applies styles to all label elements:

  • font-weight: Sets the font weight to bold.
  • margin-bottom: Adds a 10-pixel margin at the bottom of label elements.
  • color: Sets the text color to a medium gray (#555).

6. The textarea selector applies styles to all textarea elements:

  • height: Sets the height of the textarea to 150 pixels.
  • padding: Adds 10 pixels of padding inside the textarea.
  • border: Sets a 1-pixel solid border with a light gray color (#ccc).
  • border-radius: Rounds the corners of the textarea by 5 pixels.
  • margin-bottom: Adds a 15-pixel margin at the bottom of textarea elements.
  • resize: Disables resizing of the textarea.

7. The .input-group class selector applies styles to a container of input elements:

  • display: Uses a flex layout to align the input elements in a row.
  • gap: Adds 10 pixels of spacing between input elements.
  • align-items: Vertically aligns the items in the center.

8. The input[type="text"] and button selectors apply styles to text input and button elements:

  • padding: Adds 10 pixels of padding inside the elements.
  • font-size: Sets the font size to 14 pixels.
  • border: Sets a 1-pixel solid border with a light gray color.
  • border-radius: Rounds the corners of the elements by 4 pixels.

9. The button selector applies additional styles to button elements:

  • background-color: Sets the background color of the button to a blue color (#007bff).
  • color: Sets the text color to white.
  • cursor: Changes the cursor to a pointer on hover.
  • border: Removes the default button border.
  • transition: Adds a smooth transition effect for the background color change.

10. The button:hover selector applies styles when hovering over a button:

  • Changes the background color to a darker blue color (#0056b3).

11. The .count class selector applies styles to an element, possibly used to display a character count:

  • margin-top: Adds a 10-pixel margin at the top.
  • font-size: Sets the font size to 14 pixels.
  • color: Sets the text color to a medium gray (#555).

12. The @media rule applies styles only when the screen width is at most 768 pixels:

  • The .form-container gets a bottom margin of 15 pixels.
  • The .input-group layout changes to a column direction.
  • The input[type="text"] and button elements get their width adjusted to 80% and a smaller bottom margin.

This will give our find and replace tool an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: rgb(179, 176, 176);
}

.container {
  max-width: 800px;
  margin: 10px auto;
  padding: 20px;
  background-color: white;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
}

h1 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.form-container {
  display: flex;
  flex-direction: column;
}

label {
  font-weight: bold;
  margin-bottom: 10px;
  color: #555;
}

textarea {
  height: 150px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 15px;
  resize: none;
}

.input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

input[type="text"], button {
  padding: 10px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  background-color: #007bff;
  color: white;
  cursor: pointer;
  border: none;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #0056b3;
}

.count {
  margin-top: 10px;
  font-size: 14px;
  color: #555;
}

@media (max-width: 768px) {
  .form-container {
      margin-bottom: 15px;
  }
  .input-group {
      flex-direction: column;
  }
  input[type="text"], button {
      width: 80%;
      margin-bottom: 10px;
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. This JavaScript code sets up an interactive webpage feature for finding and replacing text within an input field. It uses the DOM (Document Object Model) to manipulate HTML elements and provide a user-friendly interface for these operations. Let's break down the code step by step:

1. The document.addEventListener("DOMContentLoaded", function () {...}); line waits for the HTML document to be fully loaded before executing the enclosed code. This ensures that the JavaScript code runs only after the HTML structure is ready.

2. Inside this event listener, the code starts by selecting several HTML elements using their respective IDs:

  • inputText: Represents an input field where the user can enter text.
  • findInput: Represents an input field where the user can specify the text to find.
  • replaceInput: Represents an input field where the user can specify the replacement text.
  • replaceButton: Represents a button element that triggers the text replacement.
  • countDisplay: Represents a display area where information about the number of occurrences is shown.

3. The code sets up an event listener for the replaceButton using the addEventListener method. When the button is clicked, the enclosed function is executed. This function does the following:

  1. Retrieves the values entered by the user in the findInput, replaceInput, and inputText fields.
  2. Check if both the find text and input text are provided.
  3. Creates a regular expression (RegExp) object with the find text and the "gi" flags (global search and case-insensitive).
  4. Uses the replace method of the input text to replace all occurrences of the find text with the replacement text.
  5. Counts the number of occurrences using the match method and the regular expression, or returns an empty array if no matches are found.
  6. Updates the inputText value with the replaced text and updates the countDisplay to show the number of occurrences replaced.

4. Another event listener is set up for the findInput using the addEventListener method with the "input" event. This event is triggered whenever the user types or modifies the content of the findInput field. The enclosed function does the following:

  1. Retrieves the find text and input text values.
  2. Check if both the find text and input text are provided.
  3. Creates a regular expression object with the find text and the "gi" flags.
  4. Counts the number of occurrences using the match method and the regular expression, or returns an empty array if no matches are found.
  5. Updates the countDisplay to show the number of occurrences found, or clears the display if no find text is provided.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

document.addEventListener("DOMContentLoaded", function () {
  const inputText = document.getElementById("inputText");
  const findInput = document.getElementById("findInput");
  const replaceInput = document.getElementById("replaceInput");
  const replaceButton = document.getElementById("replaceButton");
  const countDisplay = document.getElementById("countDisplay");

  replaceButton.addEventListener("click", function () {
      const find = findInput.value;
      const replaceWith = replaceInput.value;
      let text = inputText.value;

      if (find && text) {
          const regex = new RegExp(find, "gi");
          const replacedText = text.replace(regex, replaceWith);
          const count = (text.match(regex) || []).length;

          inputText.value = replacedText;
          countDisplay.textContent = `Replaced ${count} occurrences.`;
      }
  });

  findInput.addEventListener("input", function () {
      const find = findInput.value;
      const text = inputText.value;

      if (find && text) {
          const regex = new RegExp(find, "gi");
          const count = (text.match(regex) || []).length;
          countDisplay.textContent = `${count} occurrences found.`;
      } else {
          countDisplay.textContent = "";
      }
  });
});

Final Output:

Build a Find and Replace Tool using HTML, CSS, and JavaScript.gif

Conclusion:

Congratulations! You've successfully created your own find and replace tool using HTML, CSS, and JavaScript. This hands-on project has equipped you with valuable insights into web development and text manipulation. Feel free to experiment further, adding more features and functionalities to customize your tool according to your needs.

Now, go ahead and empower your text editing tasks with this versatile find and replace tool you've built from the ground up. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post