Skip to content

Commit 2cc4b15

Browse files
authored
fix: properly sanitize leading hashes in hex colors (JhaSourav07#631)
2 parents 91330a1 + 9feb3e5 commit 2cc4b15

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
@@ -14,7 +14,7 @@ const HEX_COLOR_REGEX = /^([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa
1414
*/
1515
export function isValidHex(color?: string): boolean {
1616
if (!color) return false;
17-
const cleanColor = color.replace('#', '');
17+
const cleanColor = color.replace(/^#+/, '');
1818
return HEX_COLOR_REGEX.test(cleanColor);
1919
}
2020

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

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

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

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

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

5353
/**

0 commit comments

Comments
 (0)