regex 在数据表上进行单词搜索

k4ymrczo  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(98)

需要有关数据表上单词搜索的帮助。我对编码不是很有经验。我拼凑了一个对姓氏列的搜索,它工作正常。我希望它从第一个字母开始搜索,而不是从列中的任何地方开始搜索。例如:现在像“罗宾逊”的名字,“史密森”,“桑塔格”,“罗伯逊”我的搜索找到所有的名字与“儿子”在当我开始搜索“儿子”,我宁愿它只找到桑塔格,仍然是大小写不敏感。我还需要它找到所需的名称,即使它是第二个或第三个字。例如:查找Sontag,即使在表中输入的名称为“Robertson(nee Sontag)”,但仍保留斑马条纹。““不在表中。
我的脚本代码是:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <!-- # KEEP THIS FOR THE SEARCH #### -->
<script>
// THIS SCRIPT DOES THE SEARCH ON LAST NAME ONLY
$(document).ready(function(){
var $rows = $('#myTable tr:not(:first)');

// Add stripes to odd # rows..
$('tr:nth-child(odd)').each(function() {
  $(this).addClass('zebra-stripe');
});
//Search
$("#Last-Name-Input").on("keyup", function() {
    var value = $(this).val().toLowerCase()          
      $("#myTable tr td:nth-child(1)").filter(function() {
       $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
          });
  // Re-stripe now visible row set..
  $('#myTable tr:visible').each(function(e, v) {
    if (e % 2 == 0) {
      $(this).addClass('zebra-stripe');
    } else {
      $(this).removeClass('zebra-stripe');
    }
  });
});
});
</script>

部分CSS代码为:

<style type="text/css">
.zebra-stripe {
  background-color: #E5E5E5;
}
</style>

部分HTML代码为:

<font size="3"><strong><center>Last Name Only&nbsp;<input id="Last-Name-Input" type="text" placeholder="Search ..."></strong>&nbsp;&nbsp;<em><FONT COLOR="red">or</font color></em>&nbsp;&nbsp;<STRONG>All&nbsp;&nbsp;<input id="myInput" type="text" placeholder="Search ...">&nbsp;</center></strong></font> <!-- ***** SEARCH BOX INPUTS ***** -->
<!-- <font size="3"><strong><center>Enter All&nbsp;<input id="myInput" type="text" placeholder="Search ...">&nbsp;Here</center></strong></font>--> <!-- **** SEARCH BOX INPUT ****--> 
<div style="height:3px;font-size:3px;">&nbsp;</div><!--****THIS ADJUSTS SPACING BETWEEN SEARCH BOX AND GREEN HEADING *** -->

<div style="overflow-x:auto;max-height:600px;">
<div class="div1">
<table style=" border:0px solid black;margin-left:auto;margin-right:auto; width:60%;white-space: nowrap;">
<!--<table>-->
<!--<table cellspacing="3o" border="1">-->
    <colgroup width="7%"></colgroup>
    <colgroup width="5%"></colgroup>
    <colgroup width="4%"></colgroup>
    
        <!-------------------------------------------------------------------->
    <tr>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Section Name</th>
        
    </tr></div>
         <tbody id="myTable"> <!--***** USED FOR SEARCH TO SPECIFY WHERE THE SEARCHABLE DATA STARTS ********-->
        <tr>
        <td height="33" align="left" valign=top>Robinson</td>
        <td align="left" valign=top>Frances</td>
        <td align="center" valign=top>Tranquility TB</td>   
    </tr>
    <tr>
        <td height="33" align="left" valign=top >Smithson</td>
        <td align="left" valign=top >Walter</td>
        <td align="center" valign=top >Tranquility TB</td>
    </tr>
    <tr>
        <td height="33" align="left" valign=top>Sontag</td>
        <td align="left" valign=top>Arsene</td>
        <td align="center" valign=top>Peace</td>
    </tr>
    <tr>
        <td height="33" align="left" valign=top >Robertson (nee Sontag)</td>
        <td align="left" valign=top >Elizabeth</td>
        <td align="center" valign=top >Pioneer</td>
    </tr>

我尝试了各种各样的代码片段,但都没有成功......我真的不知道在这里调整我的代码。无论我尝试什么......我的搜索根本不起作用。

vaj7vani

vaj7vani1#

1.正如我在评论中所解释的,HTML代码必须首先清理。
1.使用正则表达式来匹配姓氏的开头可能很有用。可以使用^So来完成此操作,其中^表示“开头为”,So是搜索字段中的值。要使其不区分大小写,我们使用i修饰符来修饰“caseinsensitive"。2我为“unicode”添加了u标志,因为我们可以使用重音符号或其他字符。
这是我为解决你的问题而做的

/**
 * Escape characters which have a meaning in a regular expression.
 * 
 * @param string The string you need to escape.
 * @returns The escaped string.
 */
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

/**
 * To escape HTML characters such as "<" becoming "&lt";
 *
 * @param string The string you need to escape for HTML purpose.
 * @returns The escaped string.
 */
function escapeHtml(string) {
  return $('<span></span>').text(string).html();
}

/**
 * To restripe the visible rows of the users table.
 */
function reStripeVisibleRows() {
  $('#users tbody tr:visible').each(function(i, tr) {
    $(tr).toggleClass('zebra-stripe', i % 2 != 0);
  });
}

// When the document is loaded then initialize everything.
$(document).ready(function() {
  // Stripe the rows of the users table.
  reStripeVisibleRows();
  
  // Attach the search handler for the last name column.
  $("#last-name").on('keyup', function() {
    let value = $(this).val().toLowerCase();
    let regexLastName = new RegExp(
      '^' + escapeRegExp(value.toLowerCase()), // ^ = starting with.
      'iu' // i = case insensitive, u = unicode.
    );
    
    // Look in all the last names.
    $('#users tbody td:nth-child(1)').each(function(i, td) {
      // Does the first td (the last name) match the search?
      let matches = $(td).text().match(regexLastName);
      // Toggle the parent <tr> visibility depending on that.
      $(td).parent().toggle(matches !== null);
    })
      
    reStripeVisibleRows();
  });
  
  // Attach the search handler for the full row search.
  $('#all').on('keyup', function() {
    let value = $(this).val().toLowerCase();
    let regexLastName = new RegExp(
      escapeRegExp(value.toLowerCase()),
      'iu' // i = case insensitive, u = unicode.
    );
    
    // Look in all the lines.
    $('#users tbody tr').each(function(i, tr) {
      // Does the first td (the last name) match the search?
      let matches = $(tr).text().match(regexLastName);
      // Toggle the parent <tr> visibility depending on that.
      $(tr).toggle(matches !== null);
    })
      
    reStripeVisibleRows();
  })
});
html {
  font-family: Arial, sans-serif;
  font-size: 16px;
}

#search-form {
  display: inline-flex;
  align-items: baseline; /* Align the h2 title with the text content. */
  background: #eee;
  margin-bottom: 1em;
  padding: .5em;
}

#search-form h2 {
  font-size: 1em;
  font-weight: bold;
  margin: 0 1em 0 0;
}

.separator {
  color: red;
  margin: 0 1em;
}

table {
  border: 1px solid gray;
  border-collapse: collapse;
}

table tbody tr {
  border-bottom: 1px solid silver;
}

table th,
table td {
  padding: .25em .5em;
  text-align: left;
}

table th {
  background: gray;
  color: white;
}

table tbody tr:last-child {
  border-bottom: none;
}

.zebra-stripe {
  background-color: #f8f8f8;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>

<form action="#" id="search-form">
  <h2>Search</h2>
  <div>
    <input type="text" id="last-name" placeholder="Last name starting with..."
           title="Searches all rows with a last name starting by...">
    <span class="separator">or</span>
    <input type="text" id="all" placeholder="Row contains..."
           title="Searches all rows containing...">
  </div>
</form>

<div id="table-container">
  <table id="users" class="striped">
    <thead>
      <tr>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Section Name</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Robinson</td>
        <td>Frances</td>
        <td>Tranquility TB</td>
      </tr>
      <tr>
        <td>Smithson</td>
        <td>Walter</td>
        <td>Tranquility TB</td>
      </tr>
      <tr>
        <td>Sontag</td>
        <td>Arsene</td>
        <td>Peace</td>
      </tr>
      <tr>
        <td>Robertson (nee Sontag)</td>
        <td>Elizabeth</td>
        <td>Pioneer</td>
      </tr>
    </tbody>
  </table>
</div>

同样的解决方案,但使用更多随机数据:https://codepen.io/patacra/pen/YzOxMdr

相关问题