views:

357

answers:

4

I have this

   var checkBox = e.target;

    var tableRow = checkBox.parentNode.parentNode;
    var key = tableRow.attributes["key"];
    var aKey = key.nodeValue;

at this point aKey = "[123]"

what the best way to return 123 as an int in javascript? note that aKey could just as likely be "[5555555555555555555]" so I can't just grab characters 2-4. I need something more dynamic. I was hoping this could be parsed as like a one element array, but I see this is not correct. This is really a dataKey for an Infragisitcs grid. Their support is not very helpful.

Thanks for any advice.

Cheers, ~ck in San Diego

+3  A: 

As long as your key fits into an int without overflowing, you could do

numericKey = parseInt(aKey.substr(1, aKey.length - 2))
Vinay Sajip
According to his second example, his numbers don't fit into an int. Not sure he will ever really get any numbers that big, though. He might have been exaggerating. :-)
Nosredna
If the numbers could have leading zeros, you should specify base 10 by passing 10 as the second argument to parseInt. Otherwise, it will be interpreted as an octal number.
Matthew Crumley
A: 

include

<script src="http://json.org/json2.js"&gt;&lt;/script&gt;

Which will give you a JSON object on browser which do not have it, but will use the browser implementation when available.

Then

JSON.parse(aKey);

Which will give you the array.

olliej
+2  A: 

I think if it's always in that format, you could safely use eval() to turn it into an array and get the first element.

var aKey = eval( key.nodeValue );
var nKey = aKey[0];
tvanfosson
since it's a nodeValue, I don't like this option.
Luca Matteis
A: 

Your 5555555555555555555 example exceeds the largest "integer" which can be reliably stored in JavaScript's IEEE-754 double precision floating-point format, which is 9007199254740992. Hopefully, you just made that crazy big number up and your integers don't get nearly that large.

If you really do get numbers that big, you may need to keep your number in a string, break large numbers into multiple parts, or use a bigint library.

Nosredna