Please help me to improve dynamic HTML page which gives availability to search tiles by…
- 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
- Assistant
To enhance the search functionality by interpreting commas as logical OR conditions and trimming spaces after splitting, you need to modify the
filterTilesfunction and thehighlightTextfunction to accommodate multiple search terms. Here are the necessary changes:Change the
filterTilesfunction:Replace the existing
filterTilesfunction 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
highlightTextfunction:Replace the existing
highlightTextfunction 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
renderTilesfunction, modify the call tohighlightTextto pass the array of search terms:tile.innerHTML = highlightText(paragraph, searchTerm); // Use searchTerms instead of searchTermWith 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.