Simple Text Finder Using JavaScript Tutorial
In this code we will try to do Simple Text Finder using JavaScript. The program will find a certain text in a paragraph. The trick of this code is to use dot notation replace() in order to apply a highlighted color. To learn more about this, just follow the steps below.
Getting started:
First, you have to download the bootstrap framework, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/. I also used https://jquery.com/ to simplify some JavaScript methods/functions.
The Main Interface
This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
- <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
- <style>
- .highlight{
- background:orange;
- font-weight:bold;
- }
- </style>
- </head>
- <body>
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted #ccc;"/>
- <div class="col-md-4">
- <div class="form-group">
- <input type="text" id="keyword" class="form-control"/>
- </div>
- </div>
- <div class="col-md-8">
- <p>JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for enhancing the interaction of a user with the webpage. In other words, you can make your webpage more lively and interactive, with the help of JavaScript. JavaScript is also being used widely in game development and Mobile application development.</p>
- </div>
- </div>
- </body>
- </html>
Creating the Script
This code contains the script of the application. The code will dynamically find and highlight a text. To do this just copy and write these blocks of codes inside the text editor, then save it as script.js inside the js folder.
- function textFind(keyword){
- if(keyword){
- var content = $('p').text();
- var searchText = new RegExp(keyword, "ig");
- var matches = content.match(searchText);
- if(matches){
- $("p").html(content.replace(searchText, function(match){
- return "<span class='highlight'>"+match+"</span>";
- }));
- }else{
- $('.highlight').removeClass('highlight');
- }
- }else{
- $('.highlight').removeClass('highlight');
- }
- }
- $(document).ready(function(){
- $('#keyword').on('keyup', function(){
- textFind($(this).val());
- });
- });
DEMO VIDEO
There you have it we successfully created a Simple Text Finder using JavaScript. I hope that this simple tutorial helps you to what you are looking for. For more updates and tutorials just kindly visit this site.
Enjoy Coding!Add new comment
- 700 views