Re: Padding fixed-length strings
- From: "Evertjan." <exjxw.hannivoort@xxxxxxxxxxxx>
- Date: 15 Apr 2007 08:10:21 GMT
Richard Maher wrote on 15 apr 2007 in comp.lang.javascript:
I wrote:
function fixedLength(s,n){
n = (n<0) ?0 :n
s = s.substr(0,n);
var a = [];
a.length = n - s.length + 1; // never negative <--------------
return s + a.join(' ');
};
I like it. I'll use the Array length/join(' ') at initialize time as a
sort of space$() function to preallocate a maximum space-filled
string, but then stick to substringing out of that the number of space
bytes I need for padding.
Did some testing:
alert(new Array(17).length); // 17
alert(new Array(17).join('?').length); // 16
alert(new Array('17').length); // 1 <-----------------
alert(new Array('17').join('?').length); // 2 <-------------
alert(new Array(0).length); // 0
alert(new Array(0).join('?').length); // 0
// alert(new Array(-3).length); // error
function newArray(n){
var a = [];
a.length = n;
return a;
}
alert(newArray(17).length); // 17
alert(newArray(17).join('?').length); // 16
alert(newArray('17').length); // 17 <------------------
alert(newArray('17').join('?').length); // 16 <-------------
alert(newArray(0).length); // 0
alert(newArray(0).join('?').length); // 0
// alert(newArray(-3).length); // error
;-)
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
.
- References:
- Padding fixed-length strings
- From: Richard Maher
- Re: Padding fixed-length strings
- From: Randy Webb
- Re: Padding fixed-length strings
- From: Evertjan.
- Re: Padding fixed-length strings
- From: Richard Maher
- Padding fixed-length strings
- Prev by Date: Perferred way to embed javascript into xhtml
- Next by Date: Re: MSIE Does Not Do OnMouseXXX Events On Span Elements?
- Previous by thread: Re: Padding fixed-length strings
- Next by thread: Looking for a good book to begin learning Javascript
- Index(es):
Relevant Pages
|
Loading