简体   繁体   中英

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.

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:

<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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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