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

reverse

Reverses the characters in a string.

TypeScript
Copied!
1/**
2 * Reverses the characters in a string.
3 *
4 * @param str - The input string to reverse.
5 * @returns A new string with characters in reverse order.
6 */
7export function reverse(str: string): string {
8  return str.split('').reverse().join('');
9}
  • Simplicity and Clarity

    Very concise and easy to understand implementation using built-in string and array methods.

  • Non-Destructive

    Returns a new string without mutating the original, preserving functional programming principles.

  • Wide Applicability

    Can be reused across various types of string manipulation needs, from basic tasks to more complex transformations.

  • Consistent Output

    Handles standard strings reliably regardless of input content, including whitespace and symbols.

Tests | Examples

TypeScript
Copied!
1test('reverse - normal string', () => {
2  expect(reverse('hello')).toBe('olleh');
3});
4
5test('reverse - empty string', () => {
6  expect(reverse('')).toBe('');
7});
8
9test('reverse - single character', () => {
10  expect(reverse('a')).toBe('a');
11});
12
13test('reverse - palindrome string', () => {
14  expect(reverse('madam')).toBe('madam');
15});
16
17test('reverse - with numbers and symbols', () => {
18  expect(reverse('123!abc')).toBe('cba!321');
19});

Common Use Cases

  • Palindrome Checking

    Reverse the string and compare it with the original to check if it’s a palindrome.

  • Text Animations or Effects

    Used in UI/UX for mirroring or reversing text dynamically (e.g., reversing typing animation).

  • Encoding or Obfuscation

    Simple form of text obfuscation for puzzle games or non-secure encoding scenarios.

  • Data Entry Validation

    Compare reversed versions of values for validation or formatting (e.g., IBAN or credit card checks).

  • CLI and Debugging Tools

    Display reversed output for command-line utilities or logging in reverse-chronological order.

Codebase: Utilities -> Strings -> reverse | Yevhen Klymentiev