简体   繁体   English

如何将我的过滤器搜索输入文本与我的 RegEx 匹配?

[英]How to match my filter search input text with my RegEx?

I have an image gallery where when I type in the search field #cat (for example) it will filter through the tags of my images, which are stored in a separate variable that extracts the info from a JSON file.我有一个图片库,当我在搜索字段中键入 #cat(例如)时,它会过滤我的图片标签,这些标签存储在一个单独的变量中,该变量从 JSON 文件中提取信息。

I have a RegEx which is not searching for the specific word only in the tags, but for the tags that contain partially that word as well.我有一个正则表达式,它不仅在标签中搜索特定单词,而且还搜索部分包含该单词的标签。 I need it to avoid the tags that partially contain the word.我需要它来避免部分包含该单词的标签。

HTML: HTML:

<div class="searchButton">
    <input type="text" id="inputValue" data-toggle="tooltip" placeholder="Search by name or #tag">
    <button id="searchBtn" onclick="goToPage(0,limit)" type="button">Search</button>
</div>

JS: JS:

function goToItem(filter,imgIndex,count) {
    let imagesToDisplay = getImageArray(filter, imgIndex, count);
    const imgCount = getImagesCount();
    RenderPagingView(imgCount);
    renderImages(imagesToDisplay);
} 

function getImageArray(filter, imgIndexStart, numberOfImages) {
    let filter = $("#inputValue").val().toLowerCase();        
    searchByTag = filter[0] === "#";
    regexTag = new RegExp(filter.replace(/#/g, '').replace(/,/, '|').match(/\W*(`//how to place the input field of the filter variable here ,so to watch for that word only ??`)\W*/g));
    regexTitle = new RegExp(filter.replace(/,/g, '|'));
    let filteredArrayPhotos=[];

    tmpFiltered = arrayPhotos.filter(function searchFilter (image){
    return searchByTag ? regexTag.test(image.tag) : regexTitle.test(image.title.toLowerCase());
}

If there is a better way with For loop, for example, it will suit as well.例如,如果 For 循环有更好的方法,它也将适合。

I have changed:我改变了:

regexTag = new RegExp(filter.replace(/#/g, '').replace(/ /g, '').replace(/,/, '|') );

To:至:

regexTag = new RegExp(('\\b' + filter + '\\b').replace(/#/g, '').replace(/ /g, '').replace(/,/, '|') );

And now everything is working properly.现在一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM