Thanks for the feedback.
Though...I, honestly, don't see how regular expressions would make things any faster.
The only practical use for them would be checking the beginning up to '-0x' -- and that's not very practical, at all.
var parse = {
Int: function(s, r)
{
// check parameters/arguments
if ( arguments.length < 1 ) return Number.NaN;
// initialize variables
var spectrum = { // character spectrum // lookup table
0: 0, 1: 1, 2: 2, 3: 3,
4: 4, 5: 5, 6: 6, 7: 7,
8: 8, 9: 9, a: 10, b: 11,
c: 12, d: 13, e: 14, f: 15,
g: 16, h: 17, i: 18, j: 19,
k: 20, l: 21, m: 22, n: 23,
o: 24, p: 25, q: 26, r: 27,
s: 28, t: 29, u: 30, v: 31,
w: 32, x: 33, y: 34, z: 35
}
var num = 0, // returned number
neg = false, // negetive
str = new String(s).toLowerCase(), // processed string
rad; // active radix
var index = 0; // input string traverser
valid = false; // validity of the string
// trim leading/trailing spaces
str = str.replace(/^\s+|\s+$/g ,'');
// check trimmed string length
if ( str.length < 1 )
{
str = Number.NaN;
}
else
{
// determin negativity
if ( str.charAt(index) == '-' )
{
neg = true;
index++;
}
// determin radix
if ( r )
{
if ( r >= 2 && r <= 36 )
rad = r;
else
num = Number.NaN;
}
else
{
// octal or hex
if ( str.charAt(index) == '0' )
{
valid = true; // assume 0
rad = 8;
index++;
// hex-only
if ( str.charAt(index) == 'x' )
{
valid = false; // remove assumption
rad *= 2;
index++;
}
}
else
{
rad = 10;
}
}
// check unprocessed string length
if ( !( str.length > index ) )
{
num = Number.NaN;
}
// scan unprocessed string
for ( var i = 0 ; (!isNaN(num)) && rad && index < str.length; index++ )
{
// get index of character from the active spectrum (sym-lookup)
i = spectrum[ str.charAt(index) ];
if ( i > -1 && i < rad ) // valid character
{
num *= rad; // move digits (e.g., 10 => 100 [base 10])
num += i; // increment
valid = true; // found a valid character
}
else
{
if (!valid)
num = Number.NaN; // set to NaN rather than the initial value of 0
break; // end for loop
}
}
if ( neg && (!isNaN(num)) ) // adjust for negative
num *= -1;
}
return num;
}
}
alert( ''
+ parse.Int("184") + "\n" // 184
+ parseInt("184") + "\n"
+ parse.Int("184", 12) + "\n" // 244
+ parseInt("184", 12) + "\n"
+ parse.Int("0379") + "\n" // 31 (ignores "9")
+ parseInt("0379") + "\n"
+ parse.Int("0x0FG") + "\n" // 15 (ignores "G")
+ parseInt("0x0FG") + "\n"
+ parse.Int("00zz", 35) + "\n" // 0 (ignored "zz")
+ parseInt("00zz", 35) + "\n"
+ parse.Int("0x00zz", 36) + "\n" // 55428623
+ parseInt("0x00zz", 36) + "\n"
+ parse.Int("foo") + "\n" // NaN
+ parseInt("foo") + "\n"
+ parse.Int('-1', 10) + "\n" // tests from replies
+ parse.Int('-0x01') + "\n"
+ parse.Int(' -0x81 ') + "\n" // allows leading/trailing spaces
);</PRE></BLOCKQUOTE>