JavaScript
Article
By Aurelio De Rosa

Trimming Strings in JavaScript

By Aurelio De Rosa

String trimming is one of the most common tasks that programmers deal with. Trimming functions remove whitespace from the beginning and/or end of a string. Native support for trimming was introduced in JavaScript 1.8.1, meaning that they were not part of Internet Explorer prior to IE9. This article will show you how to trim, and how you can build more flexible and powerful trimming functions.

JavaScript provides three functions for performing various types of string trimming. The first, 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"
--ADVERTISEMENT--

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.

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account