Skip to content

Commit

Permalink
Add RegExp string filtering capabilities (#362)
Browse files Browse the repository at this point in the history
  • Loading branch information
juandjara authored Mar 23, 2022
1 parent e8ca3f8 commit bd366b9
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 12 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Not released

- Implement multiple operationColumn in core functions [#347](https://github.com/CartoDB/carto-react/pull/347)
- Add RegExp string filtering capabilities [#362](https://github.com/CartoDB/carto-react/pull/362)

## 1.2

Expand Down
5 changes: 5 additions & 0 deletions packages/react-core/__tests__/filters/FilterTypes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ describe('FilterTypes', () => {

// Multiples filter values (OR)
expect(stringSearchFilter(['_test_', 'carto'], featureValue)).toBe(true);

// Regexp filtering
expect(stringSearchFilter(['\\w+RT\\w'], featureValue, { useRegExp: true })).toBe(
true
);
});
});
});
22 changes: 10 additions & 12 deletions packages/react-core/src/filters/FilterTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,18 @@ function closedOpen(filterValues, featureValue) {
// FilterTypes.STRING_SEARCH
function stringSearch(filterValues, featureValue, params = {}) {
const normalizedFeatureValue = normalize(featureValue, params);
const stringRegExp = filterValues
.map((filterValue) => {
let stringRegExp = escapeRegExp(normalize(filterValue, params));
const stringRegExp = params.useRegExp
? filterValues
: filterValues.map((filterValue) => {
let stringRegExp = escapeRegExp(normalize(filterValue, params));

if (params.mustStart) stringRegExp = `^${stringRegExp}`;
if (params.mustEnd) stringRegExp = `${stringRegExp}$`;
if (params.mustStart) stringRegExp = `^${stringRegExp}`;
if (params.mustEnd) stringRegExp = `${stringRegExp}$`;

return stringRegExp;
})
.join('|');
return stringRegExp;
});

const regex = new RegExp(stringRegExp, 'g');
const regex = new RegExp(stringRegExp.join('|'), params.caseSensitive ? 'g' : 'gi');
return !!normalizedFeatureValue.match(regex);
}

Expand All @@ -72,9 +72,7 @@ function escapeRegExp(value) {
}

function normalize(data, params) {
let normalizedData = '' + data;

if (!params.caseSensitive) normalizedData = normalizedData.toLocaleLowerCase();
let normalizedData = String(data);
if (!params.keepSpecialCharacters)
normalizedData = normalizedData.normalize('NFD').replace(normalizeRegExp, '');

Expand Down

0 comments on commit bd366b9

Please sign in to comment.