There is a <span>Текст1\nТекст2</span>

It is necessary to replace \n with a line break in JavaScript so that the browser shows:

 Текст1 Текст2 

I understand here is not just <br> replace the need to insert, but something else on the tags.
Suggest the easiest way.

  • so I understood that it’s not just necessary to insert a br replace, but something else by tags - where does this assumption come from? - Grundy
  • by the way, you can not change anything at all, just put: white-space: pre; - Grundy

2 answers 2

To pass the string inside the element as html, use the innerHTML setter:

 let elem=document.querySelector('span') elem.innerHTML=elem.innerHTML.replace(/\\n/g,'<br>') 
 <span>Луна\nсъела\nпеченьку</span> 

Or if you have real line breaks, and not as text:

 let elem=document.querySelector('span') elem.innerHTML=elem.innerHTML.replace(/\n/g,'<br>') 
 <span>Луна съела печеньку</span> 

Or without <br> s:

 let elem=document.querySelector('span') elem.innerHTML=elem.innerHTML.replace(/\\n/g,'\n') 
 span{ white-space: pre-wrap; } 
 <span>Луна\nсъела\nпеченьку</span> 

     var foo = document.querySelectorAll("span"); for (var i = 0; i < foo.length; i++) { if (foo[i].textContent.indexOf("\n")) { foo[i].innerHTML = foo[i].innerHTML.replace(/\\n/g, "<br>"); } } 
     <span>some text \n some text</span>