javascriptreactjsregexurlregex-group

Regex pattern matching every url and not filtering


So I have the following urls from an app:

1.${endpoint}/list?currentPage=1&itemsPerPage=20&orderBy=name&orderType=1

2.${endpoint}/list?current=true&currentPage=1&itemsPerPage=20&orderBy=name&orderType=1

3.${endpoint}/list?currentPage=1&filter=current&itemsPerPage=20&orderBy=name&orderType=1&searchBy=

And the following Regex expression in React:

let endpointRegexString = `${endpoint.replace('*', '')}.*`;

if (filter) {
    endpointRegexString += `.*${urlPattern}.*`;
}

Where urlPattern is a prop that can be current, hub, lapsed, etc

My problem comes when trying to match the urls with urlPattern=current because I need to match the second and third urls without matching the first. But I'm matching the first because it's matching the currentPage part with current.

I have tried several patterns but I'm not able to solve the regex, thank you!

I tried several patterns like:

endpointRegexString += '(?!.*current.*currentPage)';

or:

endpointRegexString += `\\?.*currentPage=|&currentPage=`;

But I cannot match second and third urls without matching the first one


Solution

  • Surround the search terms with word boundaries \b, ie \bcurrent\b, \bhub\b, \blapsed\b.

    This will prevent current matching currentPage, lapsed from matching elapsed, etc.

    Word boundary \b matches between a word character \w and a non word character \W, or visa versa.