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 whitespaces are created by using the computer keyboard's Space Bar and Tabs, as well as line break characters or line terminators such as
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 whitespaces around the string, but we could also trim other characters.
trim() is a built-in string method which is used to, well, trim a string. The method removes the whitespaces from both ends of a string and returns it:
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:
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
\r, e.t.c. 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
trim() works by removing the whitespaces 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
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 whitespaces 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
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 whitespaces 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 Whitespaces From Strings
Moving on, let's now see how to trim all whitespaces using Regular Expressions. So far we have only seen how to remove whitespaces from the start or end of our strings - let's now see how to remove all whitespaces.
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.
Let’s now compose a Regular Expression to handle the removal of all whitespaces from strings:
\s: Matches any whitespace symbol such as spaces, tabs, and line breaks.
+: Matches one or more of the preceding tokens (referencing
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 whitespaces 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 whitespaces and replaced them with an empty string.
When using Regular Expressions, and the
string.replace() method - you're not limited to trimming whitespaces. 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 arbitraty pattern, such as any number between
let example = "1234567890I know the man1234567890"; let show = example.replace(/^[0-9]+/, '').replace(/[0-9]+$/, ''); console.log(show); // "I know the man"
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
We've explored the
trimEnd() methods, that automatically trim whitespaces. We've then explored the use of Regular Expressions to replace patterns of whitespaces, 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