Chrome: parseInt () returns NaN

I made an AJAX call that 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 get from the server is a string, for example. "21", which now needs to be converted to a number so that JS can calculate with it. It works fine in Firefox, the output of the console.log () line is:

Received message with last message: line "21" 21

But Google Chrome does parseInt () returns this:

Received last message ID: string "21" NaN

What is wrong here?

+4
source share
3 answers

The string has a prefix of non-printing invalid characters, which leads to the fact that parseInt()it will not be able to parse the string as a number and therefore returns NaN(Not-a-Number).

, , :

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

data.length, , .

(, ), . , , parseInt(), .

, , regEx :
Regex, javascript

( -, )

.

@fero link, , char, , , .

. UTF-8, .

+5

:

console.log("Received latest message ID: " + typeof(data) + " \"" + data + "\" " + parseInt(data.match(/\d/g).join("")));

, data , , .

+1
var data = parseInt(" 21", 10);
alert(data);

It works for me on google chrome 32.0 and firefox 27

0
source

Source: https://habr.com/ru/post/1524231/


All Articles