Javascript - parseInt returns weird values ​​for WebSocket data

I get weird behavior when using parseInt ().

webSocket.onmessage = function (event) { var raw = event.data; alert(raw); var data = raw.split(":"); alert("lat:\"" + data[0] + "\" lon:\"" + data[1] + "\""); var x = parseInt(data[0]); var y = parseInt(data[1]); alert("lat:" + x + " lon:" + y); } 

The first warning exits: 100: 100 is a string sent from the server.

Second warning outputs: lat: "100" lon: "100" is normal

However, the third warning output is: lat: 1 lon: NaN

What could be the reason for this?

UPDATE:

The problem was that server-side encoding generates some invisible unwanted characters. I updated the server code and the problem went away. Working solution .

+4
source share
2 answers

I assume that your data has non-printable characters, such as spaces, tabs, etc., why you get NaN after splitting.

You can use regex to get the data as follows. Using this method, you do not need to worry about non-printing characters, since only digits are selected by regex .

 var raw = '100:100 '; var data = raw.match(/\d+/g); var x = parseInt(data[0], 10); var y = parseInt(data[1], 10); document.write('x=' + x + ' y=' + y); 

The above regex will select all digits from the raw string.

0
source

I agree with @Tushar. Thus, believe that some special characters are parsed in raw = even.data; (cannot be replicated here)

The code below is working fine, you can configure it and check:

 <script type="text/javascript"> var raw = '100 :100asd'; var data = raw.match(/[0-9]+/gm); alert(raw); // console.log(raw); var data = raw.split(":"); alert("lat:\"" + data[0] + "\" lon:\"" + data[1] + "\""); var x = parseInt(data[0]); var y = parseInt(data[1]); alert("lat:" + x + " lon:" + y); </script> 
0
source

All Articles