Extending JavaScript’s String Object

If you are the kind of programmer who works on multiple projects using different languages at the same time, I bet you sometimes can’t help mix things together and subconsciously expect that a method/function you commonly use in one language is also available in the other. And when this happens, you suddenly pause and realize that the function you are about to type doesn’t exist in the language you are currently writing. What could be worse is when you cannot instantly remember the syntax of the method you want to use and you have to scramble and look up the API documentation. The interruption can be annoying. Wouldn’t it be nice if you can simply use the same method that you are always familiar with in the other language?

The good news is that when it comes to JavaScript, this language is so flexible and powerful it can easily fix this problem.

For example in Java, there is this method s.trim() that you call on a string object s to remove any leading and trailing whitespaces. Unfortunately in JavaScript, this method is not available. Of course you can always write a separate function to implement this method, for example, mytrim(s). But wouldn’t it be nice if you can use it the same way you use it in Java? This way, you wouldn’t have to consciously remember about your mystrim(s) function and just let your fingers do the thinking and type it like the way you always do: s.trim().

Fortunately, JavaScript is a very powerful object-oriented programming language. You can easily extend the String object to add a method. This is accomplished by creating a function implementing the functionality you desire and attaching it to String.prototype. Below is a sample implementation of the trim() method.

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};

After loading the code above, you can now use s.trim(); where s is the string object.

Below is a sample html page where you can try out this feature. Create this html file and load it into your browser.

<html>
<head>
<title>Extending String object</title>
<script type="text/javascript">
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, "");
    };

    var mystring = "       hello, world        ";
    document.writeln("
<pre>");
    document.writeln("Has leading and trailing spaces: [" + mystring + "]");
    document.writeln("Spaces removed: [" + mystring.trim() + "]");
    document.writeln("</pre>
");
</script>
</head>
<body>
</body>
</html>

You should see the output like this:

Has leading and trailing spaces: [       hello, world        ]
Spaces removed: [hello, world]

If you are coming from Python and are used to the upper() method to convert characters to uppercase, you can implement the same method in JavaScript. JavaScript already has this method but it is called toUpperCase(). But if you prefer the Python way, so that you can just let your fingers do the thinking, the technique to accomplish this is the same:

String.prototype.upper = function () {
    return this.toUpperCase();
};

As you can see above, we didn’t have to write our own implementation. We simply use JavaScript’s built-in toUpperCase() function to duplicate it.

Extending JavaScript’s String object is not for everyone. This may not be a good idea to some people because this can cause confusion if one is not aware that an extension has been introduced. Some people would rather prefer implementing the functionality using a separate namespace, e.g., MyStringUtil.trim(s), instead of extending the string object. This makes it clear that an external API is being used.

Advertisements

8 thoughts on “Extending JavaScript’s String Object

  1. Excellent, concise and to the point.

    I now have a lovely String extension to mangle JSON containing Date(nnnn) constructs in a manner that the MVC.Net JsonModelBinder understands.

    If you dont mind, I’ll leave it here in case any other frustrated JSON-using .Net folks happen by.

    Thanks!

    if (String.prototype.mvcDotNetifyDates == null) String.prototype.mvcDotNetifyDates = function () {
    return this.replace(/\/(Date\(\d+\))\//, “\\/$1\\/”)
    };

      • Sorry, this is OT and I’ve sort of ended up hijacking your post but I had to correct the function above – it needs the “global” switch in the regular expression otherwise it only transforms the first matching date string.

        It should be:

        if (String.prototype.mvcDotNetifyDates == null)
        String.prototype.mvcDotNetifyDates = function () {
        return this.replace(/\/(Date\(\d+\))\//g, “\\/$1\\/”)
        };

        I’m quite sure that no-one will ever use this function but leaving something incorrect on the interwebs just irked me. I’ll back slowly away now…

  2. Pingback: Augmenting JavaScript Core Objects Revisited - SitePoint

  3. Pingback: Augmenting JavaScript Core Objects Revisited – Supreme #WordPress Blog | Supreme Factory

  4. Pingback: Augmenting JavaScript Core Objects Revisited | tutfork

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s