Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isEmptyOrWhitespace

Checks if a string is empty or consists only of whitespace characters.

TypeScript
Copied!
1/**
2 * Checks if a string is empty or consists only of whitespace characters.
3 *
4 * @param str - The string to check.
5 * @returns True if the string is empty or only whitespace.
6 */
7export function isEmptyOrWhitespace(str: string): boolean {
8  return typeof str === 'string' && str.trim().length === 0;
9}
  • Simple and Efficient

    Uses trim().length to quickly determine if a string is effectively empty without manual iteration or regex.

  • Type Safety Guard

    Ensures the input is a string before performing operations, preventing runtime errors from invalid types.

  • Whitespace-Aware

    Accurately detects strings that visually appear empty but contain spaces, tabs, or newlines.

  • Minimal Footprint

    Extremely lightweight, making it ideal for frequent use in input validation without performance impact.

Tests | Examples

TypeScript
Copied!
1test('returns true for empty string', () => {
2  expect(isEmptyOrWhitespace('')).toBe(true);
3});
4
5test('returns true for whitespace-only strings', () => {
6  expect(isEmptyOrWhitespace('   ')).toBe(true);
7  expect(isEmptyOrWhitespace('
8	')).toBe(true);
9});
10
11test('returns false for non-empty strings', () => {
12  expect(isEmptyOrWhitespace('hello')).toBe(false);
13  expect(isEmptyOrWhitespace('  hi  ')).toBe(false);
14});
15
16test('returns false for non-string input', () => {
17  expect(isEmptyOrWhitespace(null as any)).toBe(false);
18  expect(isEmptyOrWhitespace(undefined as any)).toBe(false);
19  expect(isEmptyOrWhitespace(123 as any)).toBe(false);
20});

Common Use Cases

  • Form Validation

    Prevent users from submitting forms with only whitespace in required text fields.

  • Sanitizing User Input

    Detect and handle meaningless input before processing or storing it.

  • Conditional Rendering or Display

    Avoid rendering labels, messages, or content placeholders when strings are blank or just whitespace.

  • Preprocessing Text Data

    Filter out empty or irrelevant entries when cleaning raw text data from files or user submissions.

Codebase: Utilities -> Validation -> isEmptyOrWhitespace | Yevhen Klymentiev