我正在尝试对文本框中键入的文本执行精确匹配,但不知何故,它正在作为部分匹配。我尝试了不同的选择,但无法弄清楚原因。
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>
期望:
任何建议都表示赞赏。
答案 0 :(得分:1)
您可以测试字符串是否与此模式匹配,而不是复杂的预处理:
^\[\d+\]<searchStr>\]$
与
var regex = new RegExp("^\\[\\d+\\]" + $.trim(searchStr) + "\\]$", 'gi');
这是一个更新的代码段:
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 + ' ');
}
});
});
&#13;
<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>
&#13;