UNPKG

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