PHP trim() Equivalent in JavaScript
JavaScript's String.prototype.trim() matches PHP's trim() for default whitespace trimming, but JavaScript's trim() has no second argument for a custom character set at all.
Requires review Works only under specific conditions — read the caveats before relying on it.
- PHP source
trim()- Closest JavaScript API
String.prototype.trim()
Main limitation: PHP's `trim($str, $charlist)` accepts a custom set of characters to strip; JavaScript's `.trim()` takes no arguments whatsoever — it always strips Unicode whitespace only. Stripping custom characters in JavaScript requires a regular expression, e.g. `str.replace(/^-+|-+$/g, '')`.
How to use each function
Before comparing the two, here's how trim() and String.prototype.trim() work
on their own.
PHP: trim()
trim(string $string, string $characters = " \t\n\r\0\x0B"): string
Strips characters from both the start and end of a string. With no second argument it removes the default whitespace set; passing $characters replaces that set entirely and supports range shorthand like 'a..z'. ltrim()/rtrim() strip only one side.
Returns: The trimmed string.
trim(" hello "); // "hello"
trim("--hello--", "-"); // "hello" JavaScript: String.prototype.trim()
str.trim()
Removes whitespace from both ends of a string. Takes no arguments at all — there's no way to strip a custom character set directly; that requires a regular expression via .replace(). .trimStart()/.trimEnd() trim only one side (PHP's ltrim()/rtrim() equivalents).
Returns: The trimmed string.
" hello ".trim(); // "hello" Quick mapping
| PHP | trim() |
|---|---|
| Closest JavaScript API | String.prototype.trim() |
How it differs
- PHP's
trim($str, $charlist)accepts a custom set of characters to strip; JavaScript's.trim()takes no arguments whatsoever — it always strips Unicode whitespace only. Stripping custom characters in JavaScript requires a regular expression, e.g.str.replace(/^-+|-+$/g, ''). - JavaScript's
.trim()whitespace definition (UnicodeWhiteSpaceandLineTerminator) is broader than PHP's default ASCII-only whitespace set, though for ordinary space/tab/newline input the results match. - PHP has
ltrim()/rtrim(); JavaScript's equivalents are.trimStart()/.trimEnd()(with.trimLeft()/.trimRight()as older aliases) — the naming convention differs (start/end vs. left/right, though the aliases do use left/right).
Examples
Basic whitespace trim
trim(" hello ");
// "hello" " hello ".trim();
// "hello" Custom character set requires a regex in JavaScript
trim("--hello--", "-");
// "hello" "--hello--".replace(/^-+|-+$/g, "");
// "hello" Edge cases
Edge case
If you need PHP's trim($str, $charlist) custom-character behavior in JavaScript, there is no direct method — you must build a regular expression, which is a genuinely different approach, not just a renamed function call.
References
- PHP Manual — trim — checked 2026-07-29
- MDN Web Docs — String.prototype.trim() — checked 2026-07-29
Last verified 2026-07-29.