user3108268 user3108268 - 3 months ago 10
CSS Question

How to break line after certain character in HTML?

If I have a field that contains something like:

<div class="break-field">
Something something, else else
</div>


So Javascript would kick in when it detects the comma in the field ',' and adds <\ br> after it, so you get something like:

<div class="break-field">
Something something,</ br>
else else
</div>

Answer

Use String#replace method

var ele = document.querySelector('.break-field');

ele.innerHTML = ele.innerHTML.replace(/,/g, ',<br/>')
<div class="break-field">
  Something something, else else
</div>


FYI : Since it recreating all elements it would destroy any handler attached to the child element.


UPDATE : If multiple div needs to be updated then you need to get all and iterate over them.

// get all divs
var eles = document.querySelectorAll('.break-field');

// convert to array(or use Array.from) and iterate over them
[].slice.call(eles).forEach(function(ele) {
  ele.innerHTML = ele.innerHTML.replace(/,/g, ',<br/>')
});
<div class="break-field">
  Something something, else else
</div>
<div class="break-field">
  Something something, else else
</div>
<div class="break-field">
  Something something, else else
</div>