sanitizeString
Sanitizes a string by removing dangerous characters and normalizing whitespace. Commonly used to clean user input before further processing or display.
1/**
2 * Sanitizes a string by removing dangerous characters and normalizing whitespace.
3 * Commonly used to clean user input before further processing or display.
4 *
5 * @param input - The string to sanitize.
6 * @returns A cleaned and safe string.
7 */
8export function sanitizeString(input: string): string {
9 return input
10 .replace(/[<>\\/"'`;&]/g, '') // remove potentially dangerous characters
11 .replace(/\s+/g, ' ') // collapse multiple whitespace
12 .trim(); // remove leading/trailing whitespace
13}
Removes High-Risk Characters
Strips characters often used in injection attacks (e.g.,
<
,>
,"
,'
,&
,;
), enhancing basic security.Whitespace Normalization
Collapses excessive internal whitespace to a single space and trims edges, producing a cleaner output.
Safe for Display and Logging
Reduces the likelihood of broken layouts or corrupted logs caused by malicious or malformed input.
Lightweight and Fast
Purely regex-based logic with no external dependencies ensures excellent performance and simplicity.
Tests | Examples
1test('sanitizeString - removes HTML special characters', () => {
2 expect(sanitizeString('<script>alert("x")</script>')).toBe('scriptalert(x)/script');
3});
4
5test('sanitizeString - collapses multiple spaces', () => {
6 expect(sanitizeString('hello world')).toBe('hello world');
7});
8
9test('sanitizeString - trims leading and trailing whitespace', () => {
10 expect(sanitizeString(' spaced out ')).toBe('spaced out');
11});
12
13test('sanitizeString - handles combination of symbols and spaces', () => {
14 expect(sanitizeString(` <div class="test"> hello </div> `)).toBe('div classtest hello div');
15});
16
17test('sanitizeString - empty string', () => {
18 expect(sanitizeString('')).toBe('');
19});
Common Use Cases
Sanitizing User Input Fields
Clean text from forms, comments, search bars, or chat inputs before display or storage.
Preparing Strings for Display in HTML
Prevent broken layout or script injection when rendering user-supplied content into the DOM.
Cleaning Data Before Logging or Auditing
Ensure logs remain readable and secure by stripping control characters or injection vectors.
Reducing Noise in Text Comparison
Normalize strings to improve accuracy in deduplication, diffing, or fuzzy matching.