Created
November 10, 2021 17:54
-
-
Save petsel/c18c91ce95d3d34c873bd4d01531b791 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* The tool named `toSearch` is a helper method nailed statically | |
* onto the `RegExp` constructor/namespace. It does support a way | |
* of building search terms/strings at runtime. | |
* In order to accomplish this task `RegExp.toSearch` makes use of | |
* `RegExp.escape` that's implementation takes into account that | |
* such strings might partly contain `RegExp` control characters | |
* which are not supposed to be read by the `RegExp` compiler as | |
* exactly this control characters but rather shall be an integral | |
* part of such above mentioned searches. | |
* `RegExp.toSearch` then additionally assures a "forgiving" or | |
* loose handling of whitespace sequences on both sides, the string | |
* which is source of the to be build search term as well as of all | |
* strings that are going to be searched. | |
*/ | |
(function (Object, RegExp) { | |
'use strict'; | |
function escape/*RegexPattern*/(value) { | |
return String(value).replace(/[^$.*+?|(){}[\]\\]/g, '\\$&'); | |
} | |
// escape.toString = () => 'escape() { [native code] }'; | |
Object.defineProperty(RegExp, 'escape', { | |
configurable: true, | |
writable: true, | |
value: escape, | |
}); | |
const classPatternWhiteSpaceSequence = ['[', | |
// http://es5.github.com/#WhiteSpace | |
// http://www.sql-und-xml.de/unicode-database/ogham.html | |
// - \u1680 :: OGHAM SPACE MARK | |
// - " ".charCodeAt(0).toString(16) | |
'\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000', | |
'\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008', | |
'\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF', | |
']+'].join(''); | |
function toSearch/*Pattern*/(value) { | |
return escape(value) | |
.replace( | |
RegExp(classPatternWhiteSpaceSequence, 'g'), | |
classPatternWhiteSpaceSequence, | |
); | |
} | |
// toSearch.toString = () => 'toSearch() { [native code] }'; | |
// function toSearch/*Pattern*/(value) { | |
// return escape(value).replace(/\s+/g, '\\s+'); | |
// } | |
// // toSearch.toString = () => 'toSearch() { [native code] }'; | |
Object.defineProperty(RegExp, 'toSearch', { | |
configurable: true, | |
writable: true, | |
value: toSearch, | |
}); | |
}(Object, RegExp)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment