build-query.js (1911B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */ 4 5 function escapeRegExp(str) { 6 const reRegExpChar = /[\\^$.*+?()[\]{}|]/g; 7 return str.replace(reRegExpChar, "\\$&"); 8 } 9 10 /** 11 * Ignore doing outline matches for less than 3 whitespaces 12 * 13 * @memberof utils/source-search 14 * @static 15 */ 16 function ignoreWhiteSpace(str) { 17 return /^\s{0,2}$/.test(str) ? "(?!\\s*.*)" : str; 18 } 19 20 function wholeMatch(query, wholeWord) { 21 if (query === "" || !wholeWord) { 22 return query; 23 } 24 25 return `\\b${query}\\b`; 26 } 27 28 function buildFlags(caseSensitive, isGlobal) { 29 if (caseSensitive && isGlobal) { 30 return "g"; 31 } 32 33 if (!caseSensitive && isGlobal) { 34 return "gi"; 35 } 36 37 if (!caseSensitive && !isGlobal) { 38 return "i"; 39 } 40 41 return null; 42 } 43 44 export default function buildQuery( 45 originalQuery, 46 modifiers, 47 { isGlobal = false, ignoreSpaces = false } 48 ) { 49 const { caseSensitive, regexMatch, wholeWord } = modifiers; 50 51 if (originalQuery === "") { 52 return new RegExp(originalQuery); 53 } 54 55 // Remove the backslashes at the end of the query as it 56 // breaks the RegExp 57 let query = originalQuery.replace(/\\$/, ""); 58 59 // If we don't want to do a regexMatch, we need to escape all regex related characters 60 // so they would actually match. 61 if (!regexMatch) { 62 query = escapeRegExp(query); 63 } 64 65 // ignoreWhiteSpace might return a negative lookbehind, and in such case, we want it 66 // to be consumed as a RegExp part by the callsite, so this needs to be called after 67 // the regexp is escaped. 68 if (ignoreSpaces) { 69 query = ignoreWhiteSpace(query); 70 } 71 72 query = wholeMatch(query, wholeWord); 73 const flags = buildFlags(caseSensitive, isGlobal); 74 75 if (flags) { 76 return new RegExp(query, flags); 77 } 78 79 return new RegExp(query); 80 }