diff --git a/src/lib/blacklist.js b/src/lib/blacklist.js index d796dbb10..c525b9961 100644 --- a/src/lib/blacklist.js +++ b/src/lib/blacklist.js @@ -1,6 +1,19 @@ import assertString from './util/assertString'; +/** + * Removes all characters from `str` that appear in the `chars` string. + * + * @param {string} str - The input string to modify. + * @param {string} chars - A string containing characters to remove from `str`. + * @returns {string} - The modified string with characters from `chars` removed. + */ export default function blacklist(str, chars) { assertString(str); - return str.replace(new RegExp(`[${chars}]+`, 'g'), ''); + if (typeof chars !== 'string') { + throw new Error('`chars` must be a string'); + } + // Escape special characters for use in regex + const escapedChars = chars.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); + // Remove characters in `chars` from `str` + return str.replace(new RegExp(`[${escapedChars}]+`, 'g'), ''); } diff --git a/src/lib/whitelist.js b/src/lib/whitelist.js index 3df56e71b..e60d3515c 100644 --- a/src/lib/whitelist.js +++ b/src/lib/whitelist.js @@ -1,6 +1,20 @@ import assertString from './util/assertString'; +/** + * Keeps only characters from `str` that appear in the `chars` string. + * + * @param {string} str - The input string to modify. + * @param {string} chars - A string containing characters to keep in `str`. + * @returns {string} - The modified string with only characters from `chars`. + * @throws {Error} - If `chars` is not a string. + */ export default function whitelist(str, chars) { assertString(str); - return str.replace(new RegExp(`[^${chars}]+`, 'g'), ''); + if (typeof chars !== 'string') { + throw new Error('`chars` must be a string'); + } + // Escape special characters for use in regex + const escapedChars = chars.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); + // Keep only characters in `chars` from `str` + return str.replace(new RegExp(`[^${escapedChars}]+`, 'g'), ''); }