Key Takeaways
- JavaScript provides three native functions for string trimming: trimLeft(), trimRight(), and trim(). These functions only remove whitespace characters from the beginning, end, or both ends of a string respectively.
- The enhanced versions of these functions can remove arbitrary characters, similar to PHP’s functions. These versions use the RegExp object and special characters like ‘^’ and ‘$’ to denote the beginning and end of the string respectively.
- Trimming is useful not only for removing extra spaces typed by users, but also for solving a wider range of problems when using the enhanced versions of the trim functions. For example, it can prevent login issues caused by trailing whitespaces in user registration.
trimLeft()
, strips characters from the beginning of the string. The second, trimRight()
, removes characters from the end of the string. The final function, trim()
, removes characters from both ends. Like many other languages, JavaScript’s native functions only remove whitespace characters. Conversely, PHP’s functions can remove arbitrary characters. This article will introduce PHP-like trimming functions.
trimLeft()
Let’s see how the native trimLeft()
works.
var string = " Hello world";
console.debug(string.trimLeft());
// prints "Hello world"
Notice that the spaces at the beginning of the string are removed. We can enhance this function by specifying a list of characters to remove. The enhanced version is shown below.
String.prototype.trimLeft = function(charlist) {
if (charlist === undefined)
charlist = "\s";
return this.replace(new RegExp("^[" + charlist + "]+"), "");
};
The key points of this function are the RegExp
object and the special ^
character. The RegExp
creates a regular expression object that matches text with a given pattern. In regular expressions, the ^
character denotes the beginning of the string. Please note that the input character list is case-sensitive.
The following example shows you how trimLeft()
removes spaces at the beginning of a string. This behavior is similar to that of the equivalent native function.
var string = " Hello world";
console.debug(string.trimLeft());
// prints "Hello world"
The following examples show how you can delete a given set of characters from the beginning of the string. The first example trims the lowercase characters “o”, “e”, and “l”, and the uppercase “H”. The second example trims the lowercase “h”. Since the string begins with a capital “H”, no trimming occurs.
var string = "Hello world";
console.debug(string.trimLeft("Hoel"));
// prints " world"
string = "Hi mate!";
console.debug(string.trimLeft("h"));
// prints "Hi mate!"
trimRight()
The enhanced trimRight()
function also accepts a single parameter representing the characters to be trimmed. The new trimRight()
function is shown below.
String.prototype.trimRight = function(charlist) {
if (charlist === undefined)
charlist = "\s";
return this.replace(new RegExp("[" + charlist + "]+$"), "");
};
The function is quite similar to the previous one. The only difference is the regular expression pattern. Instead of using the ^
character to denote the beginning of the string, we use the $
character, which represents the end of the string.
The next examples show how to use the trimRight()
function. The first one is very simple, and is similar to the previous ones. The second, is quite interesting because it uses not just a character list, but a POSIX character class. Character classes are shorthand notation to specify sets of characters. The example uses the W
code. W
represents non-word characters, or all characters except letters, digits, and the underscore character.
var string = "Hello world";
console.debug(string.trimRight("odl"));
// prints "Hello wor"
string = "Hi mate!";
console.debug(string.trimRight("\W"));
// prints "Hi mate"
trim()
The last function is very simple, and relies on the previous two. It trims both at the beginning and the end of the string. Its implementation is simple too, because it consists of calling trimLeft()
and then trimRight()
on the same string.
String.prototype.trim = function(charlist) {
return this.trimLeft(charlist).trimRight(charlist);
};
Some examples of using trim()
are shown below.
var string = "he loves she";
console.debug(string.trim("hes "));
// prints "lov"
string = " I write for JSPro.com ";
console.debug(string.trim());
// prints "I write for JSPro.com"
Conclusions
A trim function is useful for removing extra spaces typed by users. Often times, users aren’t even aware that they typed extra spaces. This fact could also lead to login problems if, for example, a user registered himself with a trailing whitespace. However, this is not the only use case for trimming. Using the enhanced versions of the trim functions presented in this article, you’ll also be able to solve a wider range of problems than the native ones can solve.Frequently Asked Questions (FAQs) about Trimming Strings in JavaScript
What is the purpose of the trim() method in JavaScript?
The trim() method in JavaScript is used to remove whitespace from both ends of a string. Whitespace in this context includes all the blank spaces, tab spaces, and line terminator characters like LF (Line Feed) and CR (Carriage Return). It’s important to note that this method does not change the original string but instead returns a new string. This method is particularly useful when you want to clean up user input for a form or any data that might have unnecessary or extra spaces.
How does the trim() method work with different types of whitespace characters?
The trim() method in JavaScript works with all types of whitespace characters. This includes spaces, tabs, no-break spaces, and all the line terminator characters such as LF (Line Feed), CR (Carriage Return), etc. When the trim() method is called on a string, it checks for these characters at the beginning and end of the string and removes them.
Can the trim() method remove other characters besides whitespace?
No, the trim() method in JavaScript is specifically designed to remove whitespace characters from the beginning and end of a string. It does not remove other characters. If you need to remove specific characters from a string, you might need to use other methods like replace() with a suitable regular expression.
Does the trim() method modify the original string?
No, the trim() method does not modify the original string. Instead, it returns a new string with the whitespace removed from both ends. This is because strings in JavaScript are immutable, which means they cannot be changed once they are created.
How can I use the trim() method to remove whitespace from only the beginning or end of a string?
JavaScript provides two additional methods for this purpose: trimStart() and trimEnd(). The trimStart() method removes whitespace from the beginning of a string, and the trimEnd() method removes whitespace from the end of a string. Like the trim() method, these methods also return a new string and do not modify the original string.
What happens if I call the trim() method on a string with no whitespace?
If you call the trim() method on a string that does not have any whitespace at the beginning or end, it will return the original string without any modifications. This is because the trim() method only removes whitespace from the beginning and end of a string.
Can I use the trim() method with non-string data types?
The trim() method is a string method, so it can only be used with strings. If you try to use it with a non-string data type, JavaScript will throw a TypeError. However, you can convert other data types to a string using the String() function or the toString() method before calling trim().
Is the trim() method case-sensitive?
No, the trim() method is not case-sensitive. It treats uppercase and lowercase characters the same way. It only removes whitespace characters from the beginning and end of a string, regardless of case.
How can I check if a string has whitespace at the beginning or end?
You can use the trim() method to check if a string has whitespace at the beginning or end. If the trimmed string is shorter than the original string, it means the original string had whitespace at the beginning or end.
Are there any alternatives to the trim() method in JavaScript?
Yes, there are alternatives to the trim() method in JavaScript. You can use the replace() method with a suitable regular expression to remove whitespace from a string. However, this might be more complex and less readable than simply using the trim() method.
I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.