0

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?

2 Answers 2

2

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"}
Sign up to request clarification or add additional context in comments.

Comments

1

You can split on ',' and join using <br />.

items.split(',').join('<br />')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.