Skip to content

Commit 9feb3e5

Browse files
committed
fix: properly sanitize leading hashes in hex colors
1 parent 7ee2274 commit 9feb3e5

2 files changed

Lines changed: 8 additions & 6 deletions

File tree

lib/svg/sanitizer.test.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ describe('SVG Sanitizer Utilities', () => {
4040
it('returns sanitized hex without #', () => {
4141
expect(sanitizeHexColor('#ff00ff', '000000')).toBe('ff00ff');
4242
expect(sanitizeHexColor('ff00ff', '000000')).toBe('ff00ff');
43+
// Handles multiple leading hashes gracefully
44+
expect(sanitizeHexColor('##ff00ff', '000000')).toBe('ff00ff');
4345
});
4446

4547
it('returns fallback for invalid input', () => {

lib/svg/sanitizer.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const HEX_COLOR_REGEX = /^([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa
1313
*/
1414
export function isValidHex(color?: string): boolean {
1515
if (!color) return false;
16-
const cleanColor = color.replace('#', '');
16+
const cleanColor = color.replace(/^#+/, '');
1717
return HEX_COLOR_REGEX.test(cleanColor);
1818
}
1919

@@ -26,27 +26,27 @@ export function isValidHex(color?: string): boolean {
2626
* For user-supplied input, use `sanitizeHexColor` instead.
2727
*/
2828
export function hexColor(value: string, fallback = '000000'): HexColor {
29-
const cleaned = value.replace('#', '');
29+
const cleaned = value.replace(/^#+/, '');
3030
if (HEX_COLOR_REGEX.test(cleaned)) {
3131
return cleaned as HexColor;
3232
}
33-
return fallback.replace('#', '') as HexColor;
33+
return fallback.replace(/^#+/, '') as HexColor;
3434
}
3535

3636
/**
3737
* Sanitizes a color input, ensuring it's a valid hex or falls back to a safe value.
3838
* Always returns a hex string WITHOUT the leading #.
3939
*/
4040
export function sanitizeHexColor(input: string | undefined | null, fallback: string): HexColor {
41-
if (!input) return fallback.replace('#', '') as HexColor;
41+
if (!input) return fallback.replace(/^#+/, '') as HexColor;
4242

43-
const cleanInput = input.trim().replace('#', '');
43+
const cleanInput = input.trim().replace(/^#+/, '');
4444

4545
if (HEX_COLOR_REGEX.test(cleanInput)) {
4646
return cleanInput as HexColor;
4747
}
4848

49-
return fallback.replace('#', '') as HexColor;
49+
return fallback.replace(/^#+/, '') as HexColor;
5050
}
5151

5252
/**

0 commit comments

Comments
 (0)