For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/string/trim.md.

trim es-toolkit

Removes whitespace or specified characters from the beginning and end of a string.

const trimmed = trim(str, chars);

Usage

trim(str, chars?)

Use trim when you want to remove unnecessary characters from the start and end of a string. If no specific characters are specified, it removes whitespace characters.

import { trim } from 'es-toolkit/string';

// Basic whitespace removal
trim('  hello  '); // 'hello'
trim('\t\n  hello  \r\n'); // 'hello'

// Removing specific characters
trim('--hello--', '-'); // 'hello'
trim('***hello***', '*'); // 'hello'

// Removing if any of multiple characters match
trim('##hello##world##', ['#', 'd']); // 'hello##worl'

When you specify multiple characters as an array, all characters that match any of them are removed.

import { trim } from 'es-toolkit/string';

// Specifying multiple characters as an array
trim('!!@@hello@@!!', ['!', '@']); // 'hello'

// Removing numbers and special characters
trim('123abc123', ['1', '2', '3']); // 'abc'

// Removing characters and spaces together
trim('  __hello__  ', ['_', ' ']); // 'hello'

Parameters

strstringrequired

The string to remove characters from the beginning and end.

charsstring | string[]optional

The characters to remove. Can use a string or character array. Defaults to whitespace characters.

Returns

Returns a new string with the specified characters removed from the beginning and end.

string

Errors

Throws an error if chars is a string with a length other than 1.

Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.