JavaScript
Coding
Programming
String Manipulation
Web Development

Trim string in JavaScript

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Trimming a string in JavaScript means removing whitespace from the start, the end, or both ends of the string. The standard library already gives you the right tools: trim, trimStart, and trimEnd. The main things to remember are that these methods do not modify the original string and that they only affect edge whitespace, not spaces inside the text.

Use trim() for Both Ends

The common case is removing whitespace from both sides.

javascript
1const raw = "   hello world   ";
2const cleaned = raw.trim();
3
4console.log(cleaned); // "hello world"
5console.log(raw);     // "   hello world   "

Strings are immutable in JavaScript, so trim() returns a new string. It does not change raw in place.

That behavior is important when a value is reused later. If you forget to assign the result, nothing changes.

Use trimStart() and trimEnd() When You Need One Side Only

Sometimes you want to preserve one edge exactly and remove whitespace only from the other.

javascript
1const left = "   hello";
2const right = "hello   ";
3
4console.log(left.trimStart());
5console.log(right.trimEnd());

These methods are clearer than writing a manual regular expression for a one-sided trim operation.

Trimming Does Not Remove Internal Spaces

A frequent misunderstanding is expecting trim() to collapse repeated spaces in the middle of the string.

javascript
const text = "   hello   world   ";
console.log(text.trim());

The result is "hello world", not "hello world".

If you want to normalize internal whitespace too, that is a different operation.

javascript
const text = "   hello   world   ";
const normalized = text.trim().replace(/\s+/g, " ");
console.log(normalized); // "hello world"

That distinction matters a lot in form handling and text cleanup.

trim() Is Usually Better Than a Regex for the Basic Case

Before trim() was widely available, developers often used regular expressions such as replace(/^\s+|\s+$/g, ""). That still works, but it is usually less readable than the built-in method.

javascript
const raw = "   hello   ";
const cleaned = raw.replace(/^\s+|\s+$/g, "");
console.log(cleaned);

Use the regex approach only when you are targeting very old environments or combining trimming with other custom pattern logic.

Guard Against Non-String Values

In real code, especially around forms and APIs, the value may not always be a string. Calling trim() on null or undefined throws an error.

A small helper can make the behavior explicit.

javascript
1function safeTrim(value) {
2  return typeof value === "string" ? value.trim() : "";
3}
4
5console.log(safeTrim("  hi  "));
6console.log(safeTrim(null));

Whether you return an empty string, null, or the original value depends on your application, but the important part is to stop assuming every input is a valid string.

Trimming Is Common at Input Boundaries

The best places to trim are usually the boundaries where text enters your system:

  • form submission,
  • query parameter parsing,
  • CSV import,
  • or API request normalization.

Doing it consistently at the boundary is better than scattering trim() calls throughout the rest of the application logic.

Common Pitfalls

  • Calling trim() and forgetting to use the returned string.
  • Expecting trim() to remove spaces in the middle of the text.
  • Using a regex for basic trimming when the built-in method is clearer.
  • Calling trim() on null, undefined, or non-string values.
  • Trimming inconsistently in many places instead of normalizing input once at the boundary.

Summary

  • Use trim() to remove whitespace from both ends of a JavaScript string.
  • Use trimStart() or trimEnd() when only one side should be cleaned.
  • Trimming returns a new string because JavaScript strings are immutable.
  • Internal whitespace is a separate problem from edge whitespace.
  • Add null-safe handling when trimming values from uncertain external input.

Course illustration
Course illustration

All Rights Reserved.