Andrew Rivers Andrew Rivers - 1 year ago 170
HTML Question

Convert JSON \n to HTML <br> tag

I've been developing a website using the YouTube A.P.I.

Within the

tag in the JSON file are line breaks

I need to convert these tags to HTML format


["Example description\nPlease click the link", "Another example description\nMore info"]


This question is NOT a duplicate of the linked article because:

  • It's using the YouTube API to retrieve data

  • It's necessary to edit from an array rather than the string (as
    described in the article)

  • The answers in either question could lead to different results and
    may not apply

Answer Source

You can simply use string replace in javascript:

var items = ["Example description\nPlease click the link\n\n", "Another example description\nMore info"];

var changed = => i.replace(/\n/g, '<br />'));
var div = document.querySelector("#test");
div.innerHTML = changed;
<div id="test"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download