1

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

4 Answers4

3

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>
Morteza Tourani
  • 3,506
  • 5
  • 41
  • 48
2

Fun fact, if you set the content of your tag by .innerText, rather than innerHTML. All the \n characters will be converted into < br > tag for you.

Ex:

document.getElementsByTagName('h1')[0].innerText = 'New text with a \nLine break.'

vothaison
  • 1,646
  • 15
  • 15
0

You should probably create individual nodes from each line instead of using <br> as it allows more flexibility. You could do something like this:

var description = ["Example description\nPlease click the link", "Another example description\nMore info"];
var fragment = description.reduce(function (frag, line) {
    var parts = line.split('\n');
    var container = document.createElement('div');
    var firstLine = document.createElement('p');
    var secondLine = document.createElement('a');
    firstLine.textContent = parts[0];
    secondLine.textContent = parts[1];
    secondLine.href = '#';
    container.appendChild(firstLine);
    container.appendChild(secondLine);
    frag.appendChild(container);
    return frag;
}, document.createDocumentFragment());
document.querySelector('.parent').appendChild(fragment);
<div class="parent"></div>

Here we take the description and reduce it into a documentFragment containing a container element with two children per item in the description array.

Using methods like textContent will prevent the XSS-attack vector (even if the descriptions are in your control, don't create possible XSS vulnerabilities for fun).

Olli K
  • 1,720
  • 1
  • 16
  • 17
-1

You can use a javascript replace function, and replace items by your needs:

 String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
    };

var test = ["yes, this is my example\n", "goodbye"];
console.log(test[0].replaceAll('\n', '<br>'))
Jordi Flores
  • 2,080
  • 10
  • 16