I need a function to add br under certain conditions [duplicate]

4

I want a function that adds the <br> tag when the text has no spacing, I made a Fiddle with the problem: link . This function can be done in JavaScript or PHP.

<div class="post">
    <p>kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk</p>
</div>
<h3>Queria uma função que deixe o texto acima igual ao texto abaixo.</h3>
<div class="post">
    <p>kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br>kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk</p>
</div>
    
asked by anonymous 29.10.2015 / 20:00

3 answers

11

I would not particularly use js or php to do this, you could solve the line break only by using word-wrap:break-word of css , like this:

.post {
  background-color: #FFF;
  border: 1px solid #e1e8ed;
  padding: 15px;
  border-radius: 6px;
  word-wrap: break-word;
}
<div class="post">
  <p>kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk</p>
</div>

See compatibility: Can I use?

    
29.10.2015 / 20:25
2

Is it something like this?

$(function() {
   var total = $('.post p:first').html().length;
    var line_brk = (total < 69) ? 69 : (total / 2);
    var el = $('.post p:first');
    var data = el.html();
    var t = '';
    for(var i in data) {
         t += data[i];
        if(i == line_brk) {
           t +='<br>';
        }
    }
    el.html(t);
});
    
29.10.2015 / 20:15
2

You can get the contents of the <p> element, and from it "break" text based on your logic. For example, the code below adds <br> when the text is larger than a certain size, but you can change the condition to when the text has no spaces. Note that the code can be simplified (quite) with libraries such as jQuery, but the idea is the same.

var postDiv = document.getElementsByClassName("post")[0];
var pElem = null;
for (var i = 0; i < postDiv.childNodes.length; i++) {
    var child = postDiv.childNodes[i];
    if (child.nodeType === document.ELEMENT_NODE && child.localName === "p") {
        pElem = child;
        break;
    }
}
var textSizeLimit = 69;
var pText = pElem.innerText;
if (pText.length > textSizeLimit) {
    while (pElem.hasChildNodes()) {
        pElem.removeChild(pElem.firstChild);
    }

    do {
        var lineText = pText.substring(0, textSizeLimit);
        pElem.appendChild(document.createTextNode(lineText));

        pText = pText.substring(textSizeLimit);
        if (pText.length > 0) {
            pElem.appendChild(document.createElement("br"));
        }
    } while (pText.length > 0);
}
    
29.10.2015 / 20:16