如何让bootstrap-select的data-live-search将 识别为普通空格
Hey there! I’ve dealt with this exact frustration with bootstrap-select’s live search feature before—those non-breaking spaces ( ) don’t play nice with the search functionality because they’re treated as a different character than regular spaces ( ). Here’s a simple, straightforward fix:
Quick Solution: Replace Non-Breaking Spaces Before Initializing
The key is to swap out all characters (Unicode: \u00A0) with regular spaces in your <option> text before initializing the selectpicker. This ensures the live search uses the correct space character for matching.
Step-by-Step Code
First, add this JavaScript right before you initialize bootstrap-select:
$(document).ready(function() { // Iterate over each option in the selectpicker $('.selectpicker option').each(function() { // Replace all non-breaking spaces with regular spaces const cleanedText = $(this).text().replace(/\u00A0/g, ' '); $(this).text(cleanedText); }); // Now initialize the bootstrap-select $('.selectpicker').selectpicker(); });
Full Working Example
Here’s your original code with the fix applied:
<body> <div class="container" style="width: auto;"> <select class="selectpicker" title='Choose one of the following...' data-live-search="true"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> </div> <!-- Include required dependencies --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.min.js"></script> <script> $(document).ready(function() { $('.selectpicker option').each(function() { $(this).text($(this).text().replace(/\u00A0/g, ' ')); }); $('.selectpicker').selectpicker(); }); </script> </body>
For Dynamic Options?
If you’re loading options dynamically (after page load), use the loaded.bs.select event to trigger the cleanup after the selectpicker finishes loading:
$('.selectpicker').selectpicker({ title: 'Choose one of the following...', liveSearch: true }).on('loaded.bs.select', function() { $(this).find('option').each(function() { $(this).text($(this).text().replace(/\u00A0/g, ' ')); }); // Refresh the selectpicker to apply changes $(this).selectpicker('refresh'); });
Why this works: Bootstrap-select’s live search matches against the text content of the options. By replacing with regular spaces, you make sure the search terms (like "Option 1") match exactly what’s in the options.
内容的提问来源于stack exchange,提问作者Jack Moody

