Reputation: 892
I have a string of JSON data and I need to replace every comma with a <br>
in javascript.
Here is my JSON {"Items":"beans ,rice ,flour","Quantity":"4 ,5 ,6"}
And my JSON call
jQuery(document).ready(function($) {
$.get( url, function( data ) {
$.each( data, function( i, val ) {
$( "#pantry" ).append(
'<h3>' +
'<p>' +
items +
'</p>' +
'<p>' +
val +
'</p>' +
'</h3>'
);
});
});
});
What do I need to add as a modifier?
Upvotes: 0
Views: 2082
Reputation: 1474
You could stringify the JSON object, then use the method replace
for Strings.
var test = JSON.stringify({"Items":"beans ,rice ,flour","Quantity":"4 ,5 ,6"});
var updatedTest = test.replace(/,/g, '<br>');
// Outputs:
// {"Items":"beans <br>rice <br>flour"<br>"Quantity":"4 <br>5 <br>6"}
This wont work corrctly though because it will update the commas that seperate each property.
This is more logical:
var test = JSON.parse(JSON.stringify({"Items":"beans ,rice ,flour","Quantity":"4 ,5 ,6"}));
var updatedTest = {};
for (prop in test){
updatedTest[prop] = test[prop].replace(/,/g, '<br>')
}
updatedTest = JSON.stringify(updatedTest);
// updadedTest Outputs:
// {"Items":"beans <br>rice <br>flour","Quantity":"4 <br>5 <br>6"}
Upvotes: 2
Reputation: 36511
You can split on ','
and join using <br />
.
items.split(',').join('<br />')
Upvotes: 1