How to Trim Whitespaces/Characters from a String in JavaScript

Introduction

As you aim to become a better JavaScript developer, it is expedient you understand some tricks and methods in JavaScript to save you from unnecessary hard-to-decode bugs in the future. Whenever users input string values through form fields, it is a good practice for you to remove the white spaces from the start and end of the strings and all unnecessary characters. Input is rarely clean, and unclean input can, in some cases, break an application.

In this guide, we will explore different methods on how to trim characters from strings in JavaScript, as well as when to use which.

Removing White Spaces From Strings

Whitespace is defined as an empty space, i.e. a space with no visual representation, but a space that does exist to separate two characters. These whitespace characters are created by using the computer keyboard's Space Bar and Tabs, as well as line break characters or line terminators such as \n, \t, \r.

Note: Trimming a string usually refers to trimming the left, right, or more commonly both sides of a string. Most commonly, we trim the potential whitespace around the string, but we could also trim other characters.

JavaScript provides three functions to assist us in trimming strings entering into our database or application from input fields.

Trim String Whitespace in JavaScript with trim()

trim() is a built-in string method which is used to, well, trim a string. The method removes whitespace from both ends of a string and returns it:

string.trim();

Let's create a username - with a double whitespace in the beginning and a single whitespace at the end:

let username = '  John Doe ';
let trimmed = username.trim();

console.log(trimmed);

This results in:

John Doe

trim() doesn't work in-place, as strings are immutable. It returns a trimmed string back - so we've captured the returned value and printed it.

Note: If whitespace is found between two characters, then, the whitespace is preserved. They're only trimmed from the start and end of a string.

The method is also used to remove line terminators such as \n, \t, \r, etc. For instance, say there's a nasty tab right before a serial number and a newline break after it:

let serialNumber = '\t  011-34201 \n';
console.log('Untrimmed: ', serialNumber)
console.log('Trimmed: ', serialNumber.trim());

This results in:

Untrimmed:	   011-34201 
Trimmed: 011-34201

Again, trim() works by removing the whitespace from both sides. However, sometimes, you may want to only trim one of the sides instead. This is where you'll opt to use the trimStart() and trimEnd() methods instead.

Trim Start of String with trimStart()

Similar to the trim() method and just like the name implies, trimStart() is used to trim out whitespace and line terminators only from the beginning of a string. For instance:

let company = '  Stack Abuse  ';
company.trimStart(); // 'Stack Abuse '
  
let serialNumber = '\t  011-34201 \n';
serialNumber.trimStart(); // '011-34201 \n'

In the example above, you will notice that the space at the beginning of the company name was removed. The same logic applies to the still-present newline in the serialNumber.

Trim End of String with trimEnd()

trimEnd() is a polar opposite of the trimStart() method and, just as the name implies, is used to trim out whitespace and line terminators only from the end of a string. For instance:

let company = '  Stack Abuse  ';
company.trimEnd(); // ' Stack Abuse'
  
let serialNumber = '\t  011-34201 \n';
serialNumber.trimEnd(); // '\t  011-34201'

In the example above, you will notice that instead of affecting the beginning like that of trimStart(), the end was affected by removing space and also the line terminator.

Trim All Whitespace From Strings

Moving on, let's now see how to trim all whitespace using Regular Expressions. So far we have only seen how to remove whitespace from the start or end of our strings - let's now see how to remove all whitespace.

This is possible using the JavaScript's string.replace() method, which supports Regular Expressions (RegEx) and helps find matches within a particular string. replace() takes two arguments, the first being the Regular Expression matching what we want to remove, and the second being the pattern we'd like to insert instead of the first.

If you'd like to read more about Regular Expressions - read our Guide to Regular Expressions and Matching Strings in JavaScript!

Let’s now compose a Regular Expression to handle the removal of all whitespace from strings:

  • \s: Matches any whitespace symbol such as spaces, tabs, and line breaks.
  • +: Matches one or more of the preceding tokens (referencing \s).
  • g: Placed at the end to indicate iterative searching throughout the full string.

Let's now combine this RegEx and make use of it to remove whitespace within, before and after strings:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

let sentence = '    I and the man decided   to move  ouT  ';
let trimmed = sentence.replace(/\s+/g, ''); // 'IandthemandecidedtomoveouT'
  
console.log('Untrimmed: ', sentence)
console.log('Trimmed: ', trimmed);

This results in:

Untrimmed:     I and the man decided   to move  ouT  
Trimmed: IandthemandecidedtomoveouT

In the example above, we took out whitespace characters and replaced them with an empty string.

Trim Arbitrary Characters with JavaScript

When using Regular Expressions, and the string.replace() method - you're not limited to trimming whitespace. You can really trim any pattern, and Regular Expression patterns are quite flexible.

We just need to derive a particular RegEx expression depending on the arbitrary characters you wish to trim. Suppose we want to remove a particular character from the start and a different one from the end of a string:

let example = "cccccccccccccccccccccI know the manaaaaaaaaaaaaaaaaaaaa";
let show = example.replace(/c+/, "").replace(/a+$/, "");
console.log(show); // "I know the man"

Or we could also work any arbitrary pattern, such as any number between 0 and 9:

let example = "1234567890I know the man1234567890";
let show = example.replace(/^[0-9]+/, '').replace(/[0-9]+$/, '');
console.log(show); // "I know the man"

Trimming Character From a Particular Index With JavaScript

Finally, another built-in string method can be used to trim strings, given a particular index. The substr() method substrings a string, and returns the subset as a new string. It is used to extract the parts of the string between the given starting and ending index.

To remove the first character from a string - we cut it off at index 1, and set the second parameter as the length of the string:

let username = 'John Doe';
console.log('Original Name: ', username);
  
let newName = username.substr(1, username.length);
console.log('After removing the first character: ', newName);

This results in:

Original Name: John Doe
After removing the first character: ohn Doe

Conclusion

In this guide, we've taken a look at how to trim whitespace from strings - be it from starts, ends or both ends of the string, in JavaScript.

We've explored the trim(), trimStart() and trimEnd() methods, which automatically trim whitespace. We've then explored the use of Regular Expressions to replace patterns of whitespace, with empty strings. Additionally, we've then explored the replacement of any arbitrary pattern in strings with any other pattern instead.

Finally, we've taken a look at the substr() method, to substring and trim characters with a given start and end index.

Last Updated: May 22nd, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms