Kerieks Kerieks - 6 months ago 7
Javascript Question

Replace character in javascript/jQuery not working

I'm creating an array in c# code behind which I assign a textbox these values and reading them from jQuery again... The problem is the data is not in the correct format...

When I assign the textbox the data looks like this:

[{"title":"MBONGENI NINELA","lat":"-25.9791666666667","lng":"28.1229","description":"1.227853"},{"title":"BRENTON ABRAHAMS","lat":"-25.9443","lng":"28.1409333333333","description":"4.950115"},{"title":"HUMPHREY DHLAMINI","lat":"-25.9405333333333","lng":"28.1398666666667","description":"5.341074"},{"title":"DRIVER","lat":"-26.0569333333333","lng":"28.0890666666667","description":"8.742389"},{"title":"JEROME GWABAZA","lat":"-26.0668333333333","lng":"28.1138666666667","description":"8.953844"},{"title":"GODFREY NGOMANE","lat":"-26.0439666666667","lng":"28.0585333333333","description":"9.538128"},{"title":"ISANDO BAKKIE","lat":"-26.0786666666667","lng":"28.0633666666667","description":"12.14226"},{"title":"NORMAN SCHLEICHER","lat":"-26.0086333333333","lng":"28.2524666666667","description":"12.41323"},{"title":"FAITH","lat":"-25.8726666666667","lng":"28.1856","description":"13.94629"},{"title":"ARMSTRONG MDEKAZI","lat":"-25.9270666666667","lng":"27.9988","description":"14.81507"},{"title":"PAUL CHILLIZA","lat":"-26.1017666666667","lng":"28.049","description":"15.07981"},{"title":"AMIT HARGOVAN","lat":"-25.9947","lng":"27.9635333333333","description":"16.72582"}]


But when I read the data from jQuery the data displays as:

"[{\"title\":\"MBONGENI NINELA\",\"lat\":\"-25.9791666666667\",\"lng\":\"28.1229\",\"description\":\"1.227853\"},{\"title\":\"BRENTON ABRAHAMS\",\"lat\":\"-25.9443\",\"lng\":\"28.1409333333333\",\"description\":\"4.950115\"},{\"title\":\"HUMPHREY DHLAMINI\",\"lat\":\"-25.9405333333333\",\"lng\":\"28.1398666666667\",\"description\":\"5.341074\"},{\"title\":\"DRIVER\",\"lat\":\"-26.0569333333333\",\"lng\":\"28.0890666666667\",\"description\":\"8.742389\"},{\"title\":\"AMIT HARGOVAN\",\"lat\":\"-25.9947\",\"lng\":\"27.9635333333333\",\"description\":\"16.72582\"}]"


My Google Map is not reading the values from jQuery thus displaying an empty div of where the markers/places should show. But when I add the values in manually from how it is read from the textbox it does display the map with all the markers. So I guessed that the "\" character is the problem. I have tried replacing it with a blank space, but it's not working.

This is how I tried

var marker = $('#txtMarkers').val();
var markers = marker.replace(/\\/gi, " ");


but it is not removing the "\" character. What can I do to get this right? ...I'm not used to working in javascript/jQuery and is fairly new to this, any help or suggestions will be appreciated....

Answer

Try JSON.parse as below you will get the object.

var marker = $('#txtMarkers').val();
var markersObj = JSON.parse(marker);  
console.log(markersObj) // check your object in console.