topkat-utils
Version:
A comprehensive collection of TypeScript/JavaScript utility functions for common programming tasks. Includes validation, object manipulation, date handling, string formatting, and more. Zero dependencies, fully typed, and optimized for performance.
51 lines • 2.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.allMatches = exports.firstMatch = exports.escapeRegexp = void 0;
//----------------------------------------
// REGEXP UTILS
//----------------------------------------
const logger_utils_1 = require("./logger-utils");
/**
* Will escape all special character in a string to output a valid regexp string to put in RegExp(myString)
* * Eg: from `'path.*.addr(*)'` will output `'aa\..*?\.addr\(.*?\)'` so regexp match `'path.random.addr(randomItem)'`
* * Options:
* * parseWildcard => config will replace '*' by '.*?' which is the best for 'match all until'
* * wildcardNotMatchingChars => if provided, will replace '*' by `[^${wildcardNotMatchingChars}]` instead of '.*?'. This allows wildcard not to match certains characters
*/
function escapeRegexp(str, config = {}) {
const { parseWildcard = false, wildcardNotMatchingChars } = config;
if (parseWildcard)
return str.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&').replace(/\*/g, wildcardNotMatchingChars ? `[^${wildcardNotMatchingChars}]` : '.*?');
else
return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
exports.escapeRegexp = escapeRegexp;
/** Get first match of the first capturing group of regexp
* Eg: const basePath = firstMatch(apiFile, /basePath = '(.*?)'/); will get what is inside quotes
*/
function firstMatch(str, regExp) { return (str.match(regExp) || [])[1]; }
exports.firstMatch = firstMatch;
/** Get all matches from regexp with g flag
* Eg: [ [full, match1, m2], [f, m1, m2]... ]
* NOTE: the G flag will be appended to regexp
*/
function allMatches(str, reg) {
let i = 0;
let matches;
const arr = [];
if (typeof str !== 'string')
logger_utils_1.C.error('Not a string provided as first argument for allMatches()');
else {
reg = new RegExp(reg, 'g');
while ((matches = reg.exec(str))) {
arr.push(matches);
if (i++ > 99) {
logger_utils_1.C.error('error', 'Please provide the G flag in regexp for allMatches');
break;
}
}
}
return arr;
}
exports.allMatches = allMatches;
//# sourceMappingURL=regexp-utils.js.map