Trimming Strings in JavaScript

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"

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.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • 1UnitedPower

    I have a little suggestion: Javascript provides it’s own syntax for regular expressions. Building regular expressions with the RegExp constructor should only be used, when your expression is generated dynamically, because it works significally slower.
    See: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim#Compatibility

    • http://www.audero.it/ Aurelio De Rosa

      Thank you for the comment. Have you a reference for your statement? Not because I don’t want to trust it, but to see how much “significally slower” is. Moreover, note that the examples show dinamically generated regexs, not static ones. So, you first need to convert a string into a regex before using it and that’s why I used the RegExp class.

      • 1UnitedPower

        Actually i wasn’t able to find something regexp specific. But the linchpin is, that a constructor-call is more expensive than its literal-notation-pendant. I remember crockford holding a lecture about this issue. I will try to find the video on youtube and post it after work. Additionally i’m thinking about publishing a benchmark-test on github.

        Your snippets are actually using generic expressions. But in my opinion the option to trim other characters than whitespace should not appear in a prototyped method , since it differs from API announced in ECMAScript-specification.

        • http://www.audero.it/ Aurelio De Rosa

          While I understand your concern about ECMAScript compatibility, this isn’t the point of the article. To be accurate, the point here is to show how a developer can create its own trimming functions to use where they aren’t supported but also to create a more powerful ones. It’s not very useful to be able to only strip spaces. Often you need to trim more than spaces and these functions will help you and others, especially those having a PHP background. So, the question can be: is it worth to have a more powerful function or a “faster” one? How much it can be faster on average? I’ll surely go for the first since these kind of optimizations aren’t a real problem and they can never be the cause of a bottleneck. However, your performance concern is appreciated and I thank you for reading the article.

          • 1UnitedPower

            Ah, i see your focus here. I wouldn’t add the method to the String.prototype then (to avoid confusion of users) but that’s a matter of taste and discussed at many places elsewhere, so we don’t need to break down another one.

        • 1UnitedPower

          Didn’t found crockfords lecture yet. But finished a very experimental state of my benchmarking-suite. It’s available on github (https://github.com/1UnitedPower/Benchmark.js).

  • toxcct

    There is no issue with adding your methods to the prototype directly, but at least, test that you don’t overwrite one before :
    if (!String.trim) String.prototype.trim = function() {…}

    • 1UnitedPower

      That’s not an option because he wants to extend functionallity of trim-methods. However it’s a good tutorial not an optimized ready-to-use solution, but that’s fine since tutorials should be very simple.

  • McBenny

    A useful snippet but I agree with others about the modification of a built-in function: that’s bad.
    For my personal use I just renamed your functions in “enhancedTrim”, “enhancedTrimLeft” and “enhancedTrimRight”. This way, no confusion.