UNPKG

1.72 kBJavaScriptView Raw
1import invariant from 'invariant';
2import stripDiacritics from './stripDiacritics';
3var CASE_INSENSITIVE = 'i';
4var COMBINING_MARKS = /[\u0300-\u036F]/;
5// Export for testing.
6export function escapeStringRegexp(str) {
7 !(typeof str === 'string') ? process.env.NODE_ENV !== "production" ? invariant(false, '`escapeStringRegexp` expected a string.') : invariant(false) : void 0; // Escape characters with special meaning either inside or outside character
8 // sets. Use a simple backslash escape when it’s always valid, and a \unnnn
9 // escape when the simpler form would be disallowed by Unicode patterns’
10 // stricter grammar.
11
12 return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
13}
14export default function getMatchBounds(subject, str) {
15 var search = new RegExp(escapeStringRegexp(stripDiacritics(str)), CASE_INSENSITIVE);
16 var matches = search.exec(stripDiacritics(subject));
17
18 if (!matches) {
19 return null;
20 }
21
22 var start = matches.index;
23 var matchLength = matches[0].length; // Account for combining marks, which changes the indices.
24
25 if (COMBINING_MARKS.test(subject)) {
26 // Starting at the beginning of the subject string, check for the number of
27 // combining marks and increment the start index whenever one is found.
28 for (var ii = 0; ii <= start; ii++) {
29 if (COMBINING_MARKS.test(subject[ii])) {
30 start += 1;
31 }
32 } // Similarly, increment the length of the match string if it contains a
33 // combining mark.
34
35
36 for (var _ii = start; _ii <= start + matchLength; _ii++) {
37 if (COMBINING_MARKS.test(subject[_ii])) {
38 matchLength += 1;
39 }
40 }
41 }
42
43 return {
44 end: start + matchLength,
45 start: start
46 };
47}
\No newline at end of file