Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

Please help me to improve dynamic HTML page which gives availability to search tiles by…

  1. User

    Please help me to improve dynamic HTML page which gives availability to search tiles by substrings. There is code:

    Make search more complex: if search field contains commas, they will be interpreted as logical OR. Trim spaces after splitting. Take attention to highlight all substrings. In your answer write only what needs to be changed in the code

  2. Assistant

    To enhance the search functionality by interpreting commas as logical OR conditions and trimming spaces after splitting, you need to modify the filterTiles function and the highlightText function to accommodate multiple search terms. Here are the necessary changes:

    Change the filterTiles function:

    Replace the existing filterTiles function with the following code:

    function filterTiles() {
        const searchInput = document.getElementById('searchInput').value;
        
        // Split input by comma and trim spaces
        const searchTerms = searchInput.split(',').map(term => term.trim().toLowerCase()).filter(term => term);
    
        const filteredParagraphs = paragraphs.filter(paragraph => 
            searchTerms.some(term => paragraph.toLowerCase().includes(term))
        );
    
        renderTiles(filteredParagraphs, searchTerms); // Pass the search terms for highlighting
    }
    

    Change the highlightText function:

    Replace the existing highlightText function with the following code:

    function highlightText(text, searchTerms) {
        if (!searchTerms || searchTerms.length === 0) return text; // Return unmodified text if no search terms
        const regex = new RegExp(`(${searchTerms.join('|')})`, 'gi'); // Create regex for case-insensitive matching
        return text.replace(regex, '<span class="highlight">$1</span>'); // Highlight match
    }
    

    Resulting Highlight Change in Render Function Call:

    In the renderTiles function, modify the call to highlightText to pass the array of search terms:

    tile.innerHTML = highlightText(paragraph, searchTerm); // Use searchTerms instead of searchTerm
    

    With these changes, your search functionality will recognize multiple terms separated by commas, apply logical OR logic, and highlight all matching substrings in the text accordingly.