JGV
JGV

Reputation: 5197

Regex exact text match is not working

I am trying to perform exact match of the text keyed in a textbox but, somehow it is working as partial match. I tried different options but could not figure out the cause.

RegExp.escape = function (text) {
    //escape the +,[,?... characters
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

var resultLbl = $('#ResultLbl');

$('#SearchTxtBox').bind('change keyup', function () {
  
resultLbl.text('');

var options = [];

options.push('[1]My]');
options.push('[2]My Name]');
options.push('[3]Name]');
options.push('[2]My Name]');

var searchStr = RegExp.escape($.trim($(this).val()));  

var searchArr = [];

if (searchStr != '' && searchStr != null) {
    searchStr = searchStr.replace(/\,/g, '\\ ')
    searchArr = searchStr.split('\\ ');
}

var search =  searchArr[0]; 

search = search.replace(/[.?*+^$[\]\\(){}|-]/g, '');

var regex = new RegExp($.trim(search), 'gi');

$.each(options, function (i, option) { 

if (option.match(regex) !== null) {
   resultLbl.append(option + ' ');
  }
});

 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Search:
<input type="text" id="SearchTxtBox"/>
<br/>
<label id='ResultLbl'></label>

Expectation:

Any suggestions are appreciated.

Upvotes: 1

Views: 334

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

Instead of complex pre-processing, you can just test if the string matches this pattern:

^\[\d+\]<searchStr>\]$

with

var regex = new RegExp("^\\[\\d+\\]" + $.trim(searchStr) + "\\]$", 'gi');

Here is an updated snippet:

    RegExp.escape = function (text) {
        //escape the +,[,?... characters
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    }

    var resultLbl = $('#ResultLbl');

    $('#SearchTxtBox').bind('change keyup', function () {
      
    resultLbl.text('');

    var options = [];

    options.push('[1]My]');
    options.push('[2]My Name]');
    options.push('[3]Name]');
    options.push('[2]My Name]');

    var searchStr = RegExp.escape($.trim($(this).val()));  

    var regex = new RegExp("^\\[\\d+\\]" + $.trim(searchStr) + "\\]$", 'gi');

    $.each(options, function (i, option) { 

    if (option.match(regex) !== null) {
       resultLbl.append(option + ' ');
      }
    });

 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Search:
<input type="text" id="SearchTxtBox"/>
<br/>
<label id='ResultLbl'></label>

Upvotes: 1

Related Questions