Chrome: parseInt() returns NaN

javascript

Solution

The string is prefixed with non-printable invalid chars which causes the `parseInt()` to not be able to parse the string as number and therefor returns `NaN` (Not-a-Number).

As in comment you can check this by escaping the string:

... + escape(data) + ...

You can also use `data.length` to see if the string is of the length you expect.

You need to find the source for this (probably encoding related) so you can prevent the string for being prefixed this way. If you are unable to find the source a temporary solution would be to strip the string before you pass it to `parseInt()` but this is not recommended for a final solution.

You can use for example a regEx to strip of the non-numeric chars: Regex using javascript to return just numbers

(or use something as suggested in the comments)

But in the end you will want to find the source.

Update thanks to @fero's link it indicates that the char you are getting comes from a BOM marker in your original file to indicate byte-order.

You could re-write your file without this marker or try to strip it off at server side before sending the data. If your data is UTF-8 this won't have an effect on the data itself.

Problem

I did an AJAX call which just returns a number: ``` var lastID = 0; var loading = true; // Get latest message ID $.ajax({ url: "libs/getLatestMessageID.ajax.php", dataType: "text", type: "GET", success: function(data) { lastID = data; console.log("Received latest message ID: " + typeof(data) + " \"" + data + "\" " + parseInt(data, 10)); }, }); ``` What I receive from the server is a string, e.g. "21", which now needs to be converted to a number so JS can calculate with it. In Firefox, it works fine, the output of the console.log() row is: Received latest message ID: string "21" 21 But Google Chrome makes parseInt() return this: Received latest message ID: string "21" NaN What goes wrong here?

Original source

Related problems