JavaScript: Remove Leading & Trailing Whitespace from a String

Updated: February 20, 2023 By: Khue Post a comment

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.