469,286 Members | 2,442 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,286 developers. It's quick & easy.

strpad in Javascript?`

Hi there,

I am wondering if there is a function doing the same as in PHP strpad()?

What I want to do is to make sure a string is always 2 characters long. If it is
one character the function should add a 0 in front.

Eg: make a "04" out of "4"

Is this possible?

Thank you for any hint,

Merlin
Jul 23 '05 #1
9 14338
Merlin wrote:
Hi there,

I am wondering if there is a function doing the same as in PHP strpad()?

What I want to do is to make sure a string is always 2 characters long.
If it is one character the function should add a 0 in front.

Eg: make a "04" out of "4"

Is this possible?

Thank you for any hint,

Merlin


function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
Or as a method of the string:
String.prototype.strpad=function(){
return (!isNaN(this) && this.toString().length==1)?"0"+this:this;
}

Mick
Jul 23 '05 #2
wow! Thank you Mick. I did not think that there is so much programming to do for
that.

Merlin
Mick White wrote:
Merlin wrote:
Hi there,

I am wondering if there is a function doing the same as in PHP strpad()?

What I want to do is to make sure a string is always 2 characters
long. If it is one character the function should add a 0 in front.

Eg: make a "04" out of "4"

Is this possible?

Thank you for any hint,

Merlin

function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
Or as a method of the string:
String.prototype.strpad=function(){
return (!isNaN(this) && this.toString().length==1)?"0"+this:this;
}

Mick

Jul 23 '05 #3
In article <2l************@uni-berlin.de>, Merlin <ne*********@gmx.de>
wrote:
Hi there,

I am wondering if there is a function doing the same as in PHP strpad()?

What I want to do is to make sure a string is always 2 characters long. If it
is
one character the function should add a 0 in front.

Eg: make a "04" out of "4"


You need to write it yourself. You may want to put in some error
checking.

Here is an example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Format Number</title>

<script type="text/javascript">
function formatNumber(num)
{
var displayNumber = num

if (displayNumber<= 9)
displayNumber = "0" + displayNumber;
return displayNumber;
}
</script>

</head>
<body
onload="alert(formatNumber(5));">
<p>
Format a number.</p>
</body>
</html>
Jul 23 '05 #4
JRS: In article <BG******************@twister.nyroc.rr.com>, seen in
news:comp.lang.javascript, Mick White <mw******@BOGUSrochester.rr.com>
posted at Tue, 6 Jul 2004 17:53:37 :
Merlin wrote:
Hi there,

I am wondering if there is a function doing the same as in PHP strpad()?

What I want to do is to make sure a string is always 2 characters long.
If it is one character the function should add a 0 in front.

Eg: make a "04" out of "4"

Is this possible?

Thank you for any hint,

Merlin


function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
Or as a method of the string:
String.prototype.strpad=function(){
return (!isNaN(this) && this.toString().length==1)?"0"+this:this;
}


Published code should ALWAYS be indented according to structure.

I see no need to check with isNaN; if someone wants to add a leading
zero, (a) it is permissible to do this to entities which are not decimal
numbers (e.g. to Hex number strings), (b) if the entity is not like a
number, there's probably a bigger mistake somewhere, and an error here
could be helpful.
For converting a Number to a string of at least two digits representing
the value,
function LZ(x) { return (x<0||x>=10?"":"0") + x }

Above, function strpad, if given a Number, returns either a Number or a
String. This could cause later confusion. If a zero is added, there
are two conversions of val to String.

These might be better; String is probably cheap when applied to a string
:-
function lz(s) { var t = String(s)
return t.length==1 ? "0"+t : t } // or <2 ??

function lz(s) { var t
return (t = String(s)).length==1 ? "0"+t : t } // ??

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #5
Dr John Stockton wrote:
JRS: In article <BG******************@twister.nyroc.rr.com>, seen in
news:comp.lang.javascript, Mick White <mw******@BOGUSrochester.rr.com>
posted at Tue, 6 Jul 2004 17:53:37 :
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
Or as a method of the string:
String.prototype.strpad=function(){
return (!isNaN(this) && this.toString().length==1)?"0"+this:this;
}

Published code should ALWAYS be indented according to structure.


This is surely a matter of personal preference, flush left presentation
doesn't suffer as much from the display quirks of many media as do
indented, tabbed, "n" spaced or <pre> markup. IMO.

I see no need to check with isNaN; if someone wants to add a leading
zero, (a) it is permissible to do this to entities which are not decimal
numbers (e.g. to Hex number strings), (b) if the entity is not like a
number, there's probably a bigger mistake somewhere, and an error here
could be helpful.
A good point, especially that of generating an error.



For converting a Number to a string of at least two digits representing
the value,
function LZ(x) { return (x<0||x>=10?"":"0") + x }

Above, function strpad, if given a Number, returns either a Number or a
String. This could cause later confusion. If a zero is added, there
are two conversions of val to String.
I am loath to change the type of an object that undergoes no change,
e.g. if the function is passed something that evaluates to the Number
22, I don't want to spit out "22", although it really matters little, I
suppose.

These might be better; String is probably cheap when applied to a string
:-
function lz(s) { var t = String(s)
return t.length==1 ? "0"+t : t } // or <2 ??

function lz(s) { var t
return (t = String(s)).length==1 ? "0"+t : t } // ??


lz("K") returns "0K", but it's not OK, at least in my book. And I like
the function to be somewhat descriptive, "strpad()" is a little obscure.

function addLeadingZeroToSingleDigitIfNeeded(num){
// Now we're cooking
// Test for Number, generate an error (visible to the user) upon failure
// Deal with negative numbers, or not?
// If it's a positive Number greater than 9, return it untouched
// Disgorge the value with the leading zero, if needed.
}

If you're dealing with user entry, you know the rest....

Mick
Jul 23 '05 #6
Lee
Mick White said:

Dr John Stockton wrote:

Published code should ALWAYS be indented according to structure.


This is surely a matter of personal preference, flush left presentation
doesn't suffer as much from the display quirks of many media as do
indented, tabbed, "n" spaced or <pre> markup. IMO.


None of the display quirks that I've ever seen make code
as unreadable as flush left, IMO.

Jul 23 '05 #7
Lee wrote:
Mick White said:
Dr John Stockton wrote:


Published code should ALWAYS be indented according to structure.


This is surely a matter of personal preference, flush left presentation
doesn't suffer as much from the display quirks of many media as do
indented, tabbed, "n" spaced or <pre> markup. IMO.

None of the display quirks that I've ever seen make code
as unreadable as flush left, IMO.


You're not from a background in C++ are you? But both you and I agree
that it's a matter of opinion....
I have no problem with those who format their code with tabs or
two-by-fours or whatever, but the code that I write is, for the most
part, for my own consumption. There is a place for AR folks in
programming, organization is very important.

Important to me:
Meaningful variable names.(Thanks to Dr. S for the prod)
if(Boolean){code;} Always use braces after conditional
Break out of loop/function asap.
Efficiency of the code (lot to learn here)

I must admit that 15 closing braces cascading diagonally across the page
appeals to my sense of aesthetics.

Mick

Jul 23 '05 #8
Lee
Mick White said:

Lee wrote:
Mick White said:
Dr John Stockton wrote:
Published code should ALWAYS be indented according to structure.

This is surely a matter of personal preference, flush left presentation
doesn't suffer as much from the display quirks of many media as do
indented, tabbed, "n" spaced or <pre> markup. IMO.

None of the display quirks that I've ever seen make code
as unreadable as flush left, IMO.


You're not from a background in C++ are you? But both you and I agree
that it's a matter of opinion....
I have no problem with those who format their code with tabs or
two-by-fours or whatever, but the code that I write is, for the most
part, for my own consumption. There is a place for AR folks in
programming, organization is very important.


C++ hasn't had much influence on my style. My first ten or so
years of coding was mostly FORTRAN, COBOL and Pascal, with a
touch each of LISP and Unix scripting. My second ten was mostly
C and Perl. More recently, my compiled code has been Java and
my scripting has mostly been Javascript.

You'll find that most programmers prefer some visual structure
to code. If you work in a situation where you have to share
your code with others (this forum, for example), you may find
that you have to have to adapt to the consensus standards.

Important to me:
Meaningful variable names.(Thanks to Dr. S for the prod)
if(Boolean){code;} Always use braces after conditional
Break out of loop/function asap.
Efficiency of the code (lot to learn here)


Add ease of maintenance and debugging, and you may appreciate
the advantages of lining up your brackets in a way that shows
which one closes which block.

Jul 23 '05 #9
JRS: In article <CJ******************@twister.nyroc.rr.com>, seen in
news:comp.lang.javascript, Mick White <mw******@BOGUSrochester.rr.com>
posted at Wed, 7 Jul 2004 21:15:14 :
Dr John Stockton wrote:
Published code should ALWAYS be indented according to structure.


This is surely a matter of personal preference, flush left presentation
doesn't suffer as much from the display quirks of many media as do
indented, tabbed, "n" spaced or <pre> markup. IMO.


For code which will only be read personally, agreed (I do not here mean
published to include ordinary usage in Web pages). For code written
professionally, ISTM that one should accommodate the preferences of co-
workers, and think of successors. Code presented to the public, such as
code in News, should accord with public preference; and the general
judgement is as I wrote.

Media that cannot preserve spaces are unworthy of consideration.

Code presented in News for public enlightenment should be indented, to
show good practice; code presented in News for debugging should be
indented, for ease of reading. Equally, code should normally be
"paragraphed", with for example functions separated by blank lines.

For converting a Number to a string of at least two digits representing
the value,
function LZ(x) { return (x<0||x>=10?"":"0") + x }

Above, function strpad, if given a Number, returns either a Number or a
String. This could cause later confusion. If a zero is added, there
are two conversions of val to String.


I am loath to change the type of an object that undergoes no change,
e.g. if the function is passed something that evaluates to the Number
22, I don't want to spit out "22", although it really matters little, I
suppose.


To have a leading zero, a result must be a string. IMHO, it is safer if
the type of a result is consistent; here, it is generally the case that
the result should be used as a string. I see possible problems with
LZ(Month)+LZ(Day) otherwise - in Jan..Oct, and in the first 9 days of
any month, the leading zero means string, so the + means concatenate.
But, if LZ returns a Number when a zero is not added, for Nov 10-30 and
Dec 10-31 the + will mean addition.

These might be better; String is probably cheap when applied to a string
:-
function lz(s) { var t = String(s)
return t.length==1 ? "0"+t : t } // or <2 ??

function lz(s) { var t
return (t = String(s)).length==1 ? "0"+t : t } // ??


lz("K") returns "0K", but it's not OK, at least in my book.


One might wish to have a two-digit result representing numbers N in
0..999, for example in a compact systematic name.

lz(N.toString(32).toUpperCase()) will do that, giving 0K for N=20 and V7
for 999.

And I like
the function to be somewhat descriptive, "strpad()" is a little obscure.


LZ is, of course, short for Leading Zero. It will commonly be used in
circumstances where shortness is useful; ISTM worth learning, if one
intends to use it. But this is scripting; a programmer using the method
is free to change the name, the identifiers used in it, the layout ... .

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #10

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.