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" |