Search code examples
javascripthtmljsonline-breaksyoutube-data-api

Convert JSON \n to HTML <br> tag


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

Within the description tag in the JSON file are line breaks \n

I need to convert these tags to HTML format

VideoDescriptions.push(item.snippet.description);

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

Edit:

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

Solution

  • You can simply use string replace in javascript:

    var items = ["Example description\nPlease click the link\n\n", "Another example description\nMore info"];
    console.clear();
    
    
    var changed = items.map(i => i.replace(/\n/g, '<br />')).join('');
    var div = document.querySelector("#test");
    div.innerHTML = changed;
    <div id="test"></div>