1 | import {remove as removeDiacritics} from 'diacritics';
|
2 |
|
3 | /**
|
4 | * String utilities
|
5 | */
|
6 |
|
7 | /**
|
8 | * Removes whitespace from both sides of passed string
|
9 | * @param {String} text
|
10 | * @return {String}
|
11 | */
|
12 | export const trim = (text) => {
|
13 | if (text.trim) {
|
14 | return text.trim();
|
15 | }
|
16 | return text.replace(/^\s*|\s*$/g, '');
|
17 | };
|
18 |
|
19 | /**
|
20 | * Checks if passed string is empty
|
21 | * @param {String} text
|
22 | * @return {Boolean}
|
23 | */
|
24 | export const isEmpty = (text) => trim(text) === '';
|
25 |
|
26 | /**
|
27 | * Makes regex safe string by escaping special characters from passed string
|
28 | * @param {String} text
|
29 | * @return {String} escaped string
|
30 | */
|
31 | export const rgxEsc = (text) => {
|
32 | let chars = /[-\/\\^$*+?.()|[\]{}]/g;
|
33 | let escMatch = '\\$&';
|
34 | return String(text).replace(chars, escMatch);
|
35 | };
|
36 |
|
37 | /**
|
38 | * Returns passed string as lowercase if caseSensitive flag set false. By
|
39 | * default it returns the string with no casing changes.
|
40 | * @param {String} text
|
41 | * @return {String} string
|
42 | */
|
43 | export const matchCase = (text, caseSensitive = false) => {
|
44 | if (!caseSensitive) {
|
45 | return text.toLowerCase();
|
46 | }
|
47 | return text;
|
48 | };
|
49 |
|
50 | /**
|
51 | * Checks if passed data contains the searched term
|
52 | * @param {String} term Searched term
|
53 | * @param {String} data Data string
|
54 | * @param {Boolean} exactMatch Exact match
|
55 | * @param {Boolean} caseSensitive Case sensitive
|
56 | * @param {Boolean} ignoreDiacritics Ignore diacritics
|
57 | * @return {Boolean}
|
58 | */
|
59 | export const contains = (term, data, exactMatch = false, caseSensitive = false,
|
60 | ignoreDiacritics = false) => {
|
61 | // Improved by Cedric Wartel (cwl) automatic exact match for selects and
|
62 | // special characters are now filtered
|
63 | let regexp;
|
64 | let modifier = caseSensitive ? 'g' : 'gi';
|
65 | if (ignoreDiacritics) {
|
66 | term = removeDiacritics(term);
|
67 | data = removeDiacritics(data);
|
68 | }
|
69 | if (exactMatch) {
|
70 | regexp = new RegExp('(^\\s*)' + rgxEsc(term) + '(\\s*$)',
|
71 | modifier);
|
72 | } else {
|
73 | regexp = new RegExp(rgxEsc(term), modifier);
|
74 | }
|
75 | return regexp.test(data);
|
76 | };
|