Sling Academy
Home/JavaScript/JavaScript: Remove Leading & Trailing Whitespace from a String

JavaScript: Remove Leading & Trailing Whitespace from a String

Last updated: February 20, 2023

This article is about removing leading and trailing whitespace from a string in JavaScript, a common task that you’ll likely encounter when developing web apps.

Remove Both Leading & Trailing Whitespace

This is a straightforward task and can be accomplished by using a built-in string method named trim().

Example:

const str = "    Sling Academy      ";
const trimmedStr = str.trim();

console.log(trimmedStr);
console.log("Original length: " + str.length);
console.log("Trimmed length: " + trimmedStr.length);

Output:

Sling Academy
Original length: 23
Trimmed length: 13

Only Trim Leading Whitespace

If you have a block of text that includes indentation at the beginning of each line, you may want to remove only the leading whitespace so that the text remains indented as a block. If that is the case, you can use the trimStart() method.

Example:

const str = "    Sling Academy      ";
const trimmedStr = str.trimStart();

console.log(trimmedStr);
console.log("Original length: " + str.length);
console.log("Trimmed length: " + trimmedStr.length);

Output:

Sling Academy      
Original length: 23
Trimmed length: 19

Only Trim Trailing Whitespace

If you have a block of text that includes a signature block at the end (e.g., in an email or document), you may want to remove only the trailing whitespace so that the signature remains intact. If this is the case, you can use the trimEnd() method.

Example:

const str = "    Sling Academy      ";
const trimmedStr = str.trimEnd();

console.log(trimmedStr);
console.log("Original length: " + str.length);
console.log("Trimmed length: " + trimmedStr.length);

Output:

    Sling Academy
Original length: 23
Trimmed length: 17

Using Regular Expression

Using built-in methods like the examples above is very convenient and fast. However, if for some reason you don’t like them, you can use regular expressions.

This example demonstrates how to trim leading and trailing whitespace:

const str = "     Sling Academy   ";
const trimmedStr = str.replace(/^\s+|\s+$/g, "");

console.log(trimmedStr); // "Sling Academy"

And this one shows you how to get rid of leading whitespace:

const str = "    slingacademy.com   ";
const trimmedStr = str.replace(/^\s+/, "");

console.log(trimmedStr); // "slingacademy.com   "

And here’s what we can do to make trailing whitespace go away:

const str = "    Welcome to Sling Academy   ";
const trimmedStr = str.replace(/\s+$/, "");

console.log(trimmedStr); // "    Welcome to Sling Academy"

In most cases involving trim whitespace, using regular expressions is more complicated than necessary. If you have any questions, please leave a comment. We’re more than happy to hear from you.

Next Article: 3 Ways to Reverse a String in JavaScript

Previous Article: JavaScript: Regular Expressions Cheat Sheet

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration