Skip to content

feat(whitelist, blacklist): enhance efficiency and error handling with optimizations #2572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/lib/blacklist.js
Original file line number Diff line number Diff line change
@@ -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'), '');
}
16 changes: 15 additions & 1 deletion src/lib/whitelist.js
Original file line number Diff line number Diff line change
@@ -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'), '');
}
Loading