JavaScript: String trimming and padding

When working with JavaScript in one of my projects I needed to trim strings and pad them. I googled for a solution and many sources I have got the following codes and sharing with you.

Trimming:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//trimming space from both side of the string
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
 
//trimming space from left side of the string
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
 
//trimming space from right side of the string
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

Using Trim Functions:

1
2
3
4
5
//write the code given above
var str = "  black  ";
alert("a" + str.trim() + "b");   //result "ablackb"
alert("a" + str.ltrim() + "b");  //result "ablack b"
alert("a" + str.rtrim() + "b");  //result "a blackb"

Padding:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//pads left
String.prototype.lpad = function(padString, length) {
	var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}
 
//pads right
String.prototype.rpad = function(padString, length) {
	var str = this;
    while (str.length < length)
        str = str + padString;
    return str;
}

Using Padding Functions:

1
2
3
var str = "5";
alert(str.lpad("0", 5)); //result "00005"
alert(str.rpad("0", 5)); //result "50000"
Share

7 Comments

  • By Arafat Rahman, October 31, 2008 @ 10:27 pm

    JavaScript doesn’t support trim on strings. It is very easy to implement with regular expressions.
    Thanks for the sharing.

  • By fijiwebdesign, March 9, 2010 @ 12:44 am

    You may want to trim other characters as well:

    String.prototype.trim = function(c) {
    c = (c || “\s”);
    return this.replace(new RegExp(“^[“+c+”]+|[“+c+”]+$”, “g”),””);
    };

    Eg:

    ” test\n”.trim(“\\s\\n”); // trim spaces and line breaks

  • By fijiwebdesign, March 9, 2010 @ 12:51 am

    With padding strings, it would probably be better to create an array of the length of the padding, and do Array.join() with the padding as the parameter. The reason is that arrays are mutable and thus would be able to join large strings very quickly, while a loop that mutates a string on every iteration would be significantly slower. This won’t be apparent for small strings, but will be significant for larger paddings.

  • By Clarence Fredericks, February 7, 2011 @ 10:56 pm

    I just came across a nice, customizable JavaScript library called jPaq which allows you to download just these functions into a minified JS file. Here is the link to the download page: http://jpaq.org/download/1.0.0.00003

  • By Jesse Bethke, May 9, 2011 @ 10:14 pm

    I love that you solve this by prototyping the String object. Very elegant solution.

  • By Christopher Thomas, June 26, 2012 @ 10:44 pm

    here is a potentially better solution: https://www.facebook.com/antimatterstudios/posts/10150752380719364

    to put that into a function

    function str_pad_left(string,pad,length){
    return (new Array(length+1).join(pad)+string).slice(-length);
    }

    function str_pad_right(string,pad,length){
    return (string+new Array(length+1).join(pad)).slice(0,length);
    }

    I have a suspicion that it’s faster because there is no logic, branching or other loops, it’s straight code, so deterministic, although I havent tested that, it just feels right.

  • By James Plante, August 19, 2016 @ 8:09 pm

    To build on what Christopher Thomas commented: the term “padding” refers to making a string larger by increasing its length IF it is not already the desired size. Using the above function would cut off characters if the length specified was smaller than the original strings length, which probably is not the desired result of “padding”. In other words, if I have the string ‘James’ and want to “pad it” to a size of 3, the above function would return ‘Jam’. It should instead return the string itself if the passed length is smaller than the original value. So I purpose tweaking the function to look like this:

    PS – I think using the argument names of “string” and “length” is not a good idea, so i changed them.

    function padl(str, char, size) {
    return str.length >= size ? str : (new Array(size + 1).join(char) + str).slice(-size);
    }

    Actually, there is a better way that works in all browsers except IE 11 and earlier (go figure):

    function padl(str, char, size) {
    return char.repeat(size – str.length) + str
    }

Other Links to this Post

RSS feed for comments on this post.

Leave a comment

blog