@mikezimm/fps-core-v7
Version:
Library of reusable core interfaces, types and constants migrated from fps-library-v2
65 lines • 3.13 kB
JavaScript
/**
* https://github.com/mikezimm/drilldown7/issues/499
* Extracts the first occurrence of a digit sequence of a specified length from a given string,
* optionally allowing a trailing suffix of letters.
*
* @param input - The input string to search.
* @param digitCount - The exact number of digits to look for (e.g., 5 for ZIP code).
* @param trailingCharacters - Optional. Number of trailing characters to allow (default = 0).
* @param onlyCAPS - Optional. If true, only allows trailing characters if all are uppercase (default = false).
*
* @returns The matched digit sequence (with or without suffix depending on parameters), or an empty string if no match is found.
*
* ✅ Examples:
* getDigitSequence("Zip: 48226", 5) → "48226"
* getDigitSequence("CostCenter-12345A", 5) → "" (suffix not allowed)
* getDigitSequence("Dept: 12345A", 5, 1) → "12345A"
* getDigitSequence("Region: 12345ab", 5, 2) → "12345ab"
* getDigitSequence("Region: 12345ab", 5, 2, true) → "" (suffix not all caps)
* getDigitSequence("Region: 12345AB", 5, 2, true) → "12345AB"
* getDigitSequence("ID: 1234A", 4, 2) → "1234A"
*
* ❗ Notes:
* - Uses negative lookbehind (`(?<!\\d)`) to ensure the match is not part of a longer number.
* - Uses negative lookahead (`(?!\\w)`) to prevent the match from being part of a larger word.
* - Underscores `_` and dashes `-` are considered non-word characters, so they count as boundaries.
* - `|` and `/` are also boundary-friendly in this regex, as they are not word characters.
*/
export function getDigitSequence(input, digitCount, trailingCharacters = 0, onlyCAPS = true) {
if (!input || digitCount < 1)
return '';
const digitGroup = `\\d{${digitCount}}`;
// Construct the trailing character group if needed
let trailingGroup = '';
if (trailingCharacters > 0) {
const letterPattern = onlyCAPS ? '[A-Z]' : '[A-Za-z]';
trailingGroup = `${letterPattern}{1,${trailingCharacters}}`;
}
// Compose the full pattern in readable blocks
const patternString = [
`(?<!\\d)`,
`(${digitGroup})`,
trailingGroup,
`(?!\\w)` // Not followed by a word character
].join('');
const regex = new RegExp(patternString);
const match = input.match(regex);
return match ? match[0] : '';
}
/**
* https://github.com/mikezimm/drilldown7/issues/499
* Use this option to get the number sequence based on extra characters but only include the number part
* @param input
* @param digitCount
* @param trailingCharacters
* @param onlyCAPS
* @returns
*/
export function getDigitSequenceTrimmed(input, digitCount, trailingCharacters = 0, onlyCAPS = false) {
const fullMatch = getDigitSequence(input, digitCount, trailingCharacters, onlyCAPS);
if (!fullMatch)
return '';
// Always remove trailing non-digit characters from the match
return fullMatch.replace(/[^0-9]+$/, '');
}
//# sourceMappingURL=getDigitSequence.js.map