Search to remove


by Jeremy Caudle
code

I wanted to try and build a search form that would place tags around the search terms found within the page, but I’ve had some trouble sorting how to do that. So I built a silly thing that just removes the words or letters you enter from the text within the paragraph. Pointless, but it’s one step towards a solution.

This is a thing that I thought would be something quick. Turns out, it is not the easiest thing to do. So I'm going to try it another day.

View the code:

HTML and JS
<section class="code-block">
            
            <div class="search-form">
                <label for="search-input">Enter some words or letters to remove:</label>
                <input type="text" id="search-input">
                <button id="search-button">Search</button>
            </div>
            
            <p id="search-within">This is a thing that I thought would be something quick. Turns out, it is not the easiest thing to do. So I'm going to try it another day.</p>
        </section>
        
        <script>

            // ---------        
            // Variables
            // ---------
            const searchText = document.getElementById('search-input');
            const searchButton = document.getElementById('search-button');
            const searchContents = document.getElementById('search-within');


            // ---------
            // Functions
            // ---------
        
                function splitString(stringToSplit, separator) {
                    let arrayofStrings = stringToSplit.split(separator);
                    console.log('The original string is: ', stringToSplit);
                    console.log('The separator is: '. separator);
                    console.log('The array has ', arrayofStrings.length, ' elements: ', arrayofStrings.join(' / '));
                    console.log(arrayofStrings);
                    return arrayofStrings;
                };


            // ---------        
            // Events
            // ---------
            searchButton.addEventListener('click', () => {
                const textToSearch = searchContents.innerHTML;
                let searchQuery = searchText.value;
                console.log(searchQuery);
                let arrayofStrings = splitString(textToSearch, searchQuery);
                console.log('Search button clicked.' + ' ' + searchQuery);
                console.log(textToSearch.search(searchQuery));
                searchContents.innerHTML = arrayofStrings.join('');
            });

        </script>
CSS
.code-block {
                width: 22em;
                margin: 1rem auto;
                padding: 1rem;
                border-radius: 1rem;
                text-align: center;
                background-color: aquamarine;
            }