String trimming

In modern browsers, JavaScript has a .trim() function on the String object. What it does is simple, it removes the extra white space before and after the string.

var text = "     I have space before and after        ";
var trimmed = text.trim();
console.log(trim); // "I have space before and after"

That's good and all, but what if we want to do the same on older browsers? The solution is simple, we can check if the browser supports trimming, if not we add our own method to the String object. We can use Regex to remove the spaces.

    if (!"".trim) {
        String.prototype.trim = function(){
            return (this+"").replace(/^\s+/,'').replace(/\s+$/,'');

Here is an exercise for you. Try to re-implement .trimLeft() and .trimRight().


There are no comments added yet.

Let's hear your thoughts

For my eyes only