views:

126

answers:

4

Hey guys,

there are lots of scripts out there to trim a string in javascript, but none how to Left Trim String.

This is what I use to trim:

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

But I would like to change this a little and create a new function called leftTrim that only removes the leading space. My regex is pretty limited, so any help is much appreciated.

Cheers

+4  A: 

Use:

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

In the regex the:

  • ^ means "from the beginning of the string"
  • \s means whitespace character class
  • + means one-or more (greedy)

so....

  • ^\s+ means "one or more consecutive whitespace characters from the beginning of the class"

Note: The g flag at the end of your regex is unnecessary as the anchors (^ and $) explicitly define what will match. There cannot be multiple matches.

See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp for details on regex syntax in javascript

Jonathan Fingland
Note: The /g (global) modifier is not necessary and may make it a little less efficient.
Jesper
What is `g` BTW? You missed that.
Adeel Ansari
thanks Jesper, I was in the process of editing it already when you wrote that. @Vinegar, `g` means `global match` and is used for finding multiple matches
Jonathan Fingland
Cheers Jon, thanks for the explanation!
sparkyfied
+1  A: 
String.prototype.leftTrim = function() {
        return this.replace(/^\s+/,"");
}
igor
+1  A: 

Very simple, the regex needs a small change:

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

See also:

Jesper
A: 

I've already answered a similar question just a few moments ago, but here's my solution to your question.

String.prototype.trimLeft = String.prototype.trimLeft || function () {
    var start = -1;

    while( this.charCodeAt(++start) < 33 );

    return this.slice( start, this.length);
};

The above solution is based on Ariel Flesler fast trim function and the fact that Firefox 3.5 and above has a built-in trimLeft method on the String object.

Ionuț G. Stan