In comp.lang.javascript message <
[email protected].
net>, Wed, 19 Sep 2007 20:04:33, Steve Robinson <stephen.p.robinson.butn
(e-mail address removed)> posted:
In the FAQ section 4.6 "How do I convert a Number into a String with exactly
2 decimal places?" there is an example with the following line of code:
if (S.search && S.search(/\D/)!=-1) { return ''+X }
Page <URL:
http://www.merlyn.demon.co.uk/js-valid.htm> is partly about
RegExps, and its links should show that the Boolean is true is S
contains any non-digit.
That FAQ section is out of date. The FAQ maintainer knows that, and
knows where to look for better code; the link is in section 4.6.
It is reasonable to expect S.search to be true. Of course, if the coder
believes that it may not be true, then S.search(/\D/) should not be
executed. But just cutting out the part which would fail is folly; and
is this case makes the function capable of returning bad strings.
Something should be done instead - preferably equivalent (in which case
there's little point in trying the first code).
If S.search will not do, the line should be substituted by one such as
if (+S>=1e21) { return ''+X }
where 1e21 marks the point at which String(N) starts to use e-format
(I've not checked where that is on all browsers; TL may know, JL would).
Or if (!(+S<e21)) return ''+X
which also deals correctly with undefined K.
The previous paragraph has been tested, though insufficiently for actual
use; I prefer the version currently on my site.
The previous line of FAQ code is inefficient.
FAQ 4.6 para 5 word 1 - "Most" should be "Many". Posters here have
provided many routines without that fault, enough to case "Most" into
doubt.