Vanilla JavaScript append <br> tag after a certain amount of characters in a string

Viewed 1187

Need some help with a little JavaScript DOM Manipulation to separate out a string onto new lines.

I have a single wrapping div around a string...

<div id= "customer-comments">
  // Div contains text of comments & no other wrapping HTML tags
Customer comment 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula neque. Aenean urna nisi, rutrum ac neque eu, aliquet aliquam ligula. Customer comment 2 - Etiam venenatis lacus quam, et imperdiet risus tempor quis. Aenean elit justo, fermentum ac leo vel, bibendum mattis est. Vestibulum sed condimentum mi, id ullamcorper libero
</div>

I am trying to use vanilla js to append a <br> tag after a specific amount (120 characters) to the string. I am using a frontend interface (profound) to load the screen & there is a feature to add onload JavaScript events to specific screens so I am trying some of the vanilla js below.

// Add new lines for customer comments display panel
let comments = document.getElementById('customer-comments').innerText; // grab comment string in div

function newLines(str) {
    if (str.length >= 120) {
        let result = '';
        while (str.length > 0) {
            result += str.substring(0, 120) + '<br>';
            str = str.substring(120);
        }
        return result;
    }
   return str;
}

newLines(comments);

Appreciate the help

Thank you

5 Answers

You can do it with a basic regular expression instead of looping and string manipulation.

var out = document.querySelector("#foo");
var text = out.textContent;
var str = text.replace(/(.{10})/g, '$1<br/>');
out.innerHTML = str;
<div id="foo">1234567890123456789012345678901234567890123456789012345678901234567890</div>

You can use something like this:

<div id= "customer-comments">
    Customer comment 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula neque. Aenean urna nisi, rutrum ac neque eu, aliquet aliquam ligula. Customer comment 2 - Etiam venenatis lacus quam, et imperdiet risus tempor quis. Aenean elit justo, fermentum ac leo vel, bibendum mattis est. Vestibulum sed condimentum mi, id ullamcorper libero
</div>
<br>
<p>Split Up:</p>
<br>
<div id="div2"></div>

<script>
    function chunk(str, n) {
        var ret = [];
        for(var i = 0; i < str.length; i += n) ret.push(str.substr(i, n))
        return ret;
    };

    let commentsText = document.getElementById('customer-comments').innerText;
    document.getElementById("div2").innerHTML = chunk(commentsText, 120).join('<br>');
</script>

This script will count the letters and check how many words will fit in the given number of letters. It will then add a tag after the word is completed without cutting it

var max = 120;    // Number of letters
var str = '<br>'; // Add <br> tag or something else

var wrapEl = document.getElementById('customer-comments');
var w = wrapEl.innerText.split(' ');
var sum = 0;
var comp = 0;
var l = 0;
for (let i = 0; i < w.length; i++) {
    sum = w[i].length + sum;
    if (sum >= max) { w.splice(l, 0, str); sum = 0; comp = 0; } else { comp = sum; l = i + 1; }
}

wrapEl.innerHTML = w.join(' ');
<div id="customer-comments">
    Customer comment 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula neque. Aenean urna
    nisi, rutrum ac neque eu, aliquet aliquam ligula. Customer comment 2 - Etiam venenatis lacus quam, et imperdiet
    risus tempor quis. Aenean elit justo, fermentum ac leo vel, bibendum mattis est. Vestibulum sed condimentum mi,
    id ullamcorper libero
</div>

And with a simple loop, by adding a char on each iteration and on key char add br

var str="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)."
var x = 0;
var newStr =""
for(var i = 0; i < str.length; i++){
  if(x == 120){
    newStr +="<br>"
    x=0
  }
  newStr += str[i]
  x++;
}
console.log(newStr)

You could create a function that takes params for the string, the amount you wish to loop over, as well as what kind of element to break the string into along with a class attribute.

Within the function a for loop that splits and pushes the values within the loop into an array. Once the array is constructed, loop over the array and assign each value to span tags that are styled to display as block level elements.

You not only get control over the amount of loops per string, but also what kind of element you wish to create and add a class attribute to the element for styling.

// get the str using textContent
var str = document.getElementById('str');
// function that runs a for loop and checks if the character
// counted in that string exceeds a given number (num), if so
// push the result of the loop between the remainder and num // into an array value repeat this process. 
// Loop over the resulting array and create span tags for each
// value within the arr. Assign a class that displays as a 
// block level element, affectively creating a new line. 
function formatStr(str, num, el, attr) {
  var result = [];
  for (var i = 0; i < str.length; i += num) {
    result.push(str.substr(i, num));
  }
  var output = '';
  for (let j in result) {
    output += `<${el}${attr}>${result[j]}</${el}>`;
  }
  return output;
}
// reset the original displayed div to the newly formatted
// span elements with 10 characters per line
// and add a class block-level with a block display
document.getElementById("str").innerHTML = formatStr(str.textContent, 10, 'span', ' class="block-level"');
// display the original string reformtted to div elements 
// with 20 characters per line and add a class of
// yellow-bg
document.getElementById("results").innerHTML = formatStr(str.textContent, 20, 'div', ' class="yellow-bg"');
// display the original string with 5 perline to p tags
// with no added class
document.getElementById("results2").innerHTML = formatStr(str.textContent, 5, 'p', '');
.block-level {
  display: block;
}

.yellow-bg {
  background-color: yellow;
  padding: 5px;
  margin-bottom: 3px;
}
<div id="str">1234567890123456789012345678901234567890123456789012345678901234567890</div>


<div id="results"></div>
<div id="results2"></div>

strong text

Related