I have JSON file like this below, inside data.json
.
{
"usfood":[
{
"fruits":"This is apple.\\nWe harvest every Spring."
}
],
"ukfood":[
{
"fruits":"This is melon.\\nWe harvest every Winter."
}
]
}
I have HTML like this below, inside index.php
.
<p id="food_description"></p>
I have jQuery code like this below, inside <script>
tag of index.php
.
$(document).on('ready',function(){
$.getJSON("data.json",function(data) {
$('#food_description').html(replaceBreak(data['usfood'][0].usfood));
})
});
function replaceBreak(str){
return str.replace(/\n\r?/g, "<br />");
}
Result: The html element in the browser shows the original string
This is apple.\\nWe harvest every Spring.
I am guessing, the issue is the replaceBreak
function.
How can I improve my code to successfully replace \\n
with <br />
?
At the same time, it might be the order of codes.
I also tried return str.replace("\n", "<br />");
return str.replace(/\n/g, "<br />");
You need to use booth string
return str.replace("\\n", "<br />");