4

My JavaScript variable contains a string:

{"start":{"lat":19.0759842,"lng":72.87765630000001},"end":{"lat":18.5206624,"lng":73.8567415},"waypoints":[[18.8753235,73.52948409999999]]}

But when I show it into HTML component, it looks like:

{"start":{"lat":19.0759842,"lng":72.87765630000001},"end":{"lat":18.5206624,"lng":73.8567415},"waypoints":[[18.8753235,73.52948409999999]]}
Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53
chaitanya dalvi
  • 1,539
  • 2
  • 17
  • 25

4 Answers4

5

Output the string as HTML instead of plain text so the HTML entity " is rendered correctly.

var s = "{"start":{"lat":19.0759842,"lng":72.87765630000001},"end":{"lat":18.5206624,"lng":73.8567415},"waypoints":[[18.8753235,73.52948409999999]]}";

//Incorrect with jQuery
$("#incorrect-jquery").text(s);

//Correct with jQuery
$("#correct-jquery").html(s);

//Incorrect with plain JavaScript
document.getElementById("incorrect-js").textContent = s;

//Correct with plain JavaScript
document.getElementById("correct-js").innerHTML = s;
div {
  margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<strong>Incorrect with jQuery</strong>
<div id="incorrect-jquery"></div>

<strong>Correct with jQuery</strong>
<div id="correct-jquery"></div>

<strong>Incorrect with plain JavaScript</strong>
<div id="incorrect-js"></div>

<strong>Correct with plain JavaScript</strong>
<div id="correct-js"></div>
Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53
2

var text1 = '{&quot;start&quot;:{&quot;lat&quot;:19.0759842,&quot;lng&quot;:72.87765630000001},&quot;end&quot;:{&quot;lat&quot;:18.5206624,&quot;lng&quot;:73.8567415},&quot;waypoints&quot;:[[18.8753235,73.52948409999999]]}';
var text2 = text1.replace(/&quot;/g, '\"');

alert('Your data\n' + text1);

alert('Required data\n' + text2);
Muhammad Suleman
  • 2,892
  • 2
  • 25
  • 33
0

if you are try dispay json data in view blade in laravel try to do this

<php echo $data ?>

or

@php echo $data; @endphp instead of {{ $data }}

Arty.Simon
  • 844
  • 2
  • 7
  • 21
-1

use decodeURI javascript function to show example

var s= decodeURI('your string');
Parasmani Batra
  • 207
  • 1
  • 5