admin 管理员组文章数量: 1086019
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-ments">
// Div contains text of ments & no other wrapping HTML tags
Customer ment 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula neque. Aenean urna nisi, rutrum ac neque eu, aliquet aliquam ligula. Customer ment 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 ments display panel
let ments = document.getElementById('customer-ments').innerText; // grab ment 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(ments);
Appreciate the help
Thank you
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-ments">
// Div contains text of ments & no other wrapping HTML tags
Customer ment 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula neque. Aenean urna nisi, rutrum ac neque eu, aliquet aliquam ligula. Customer ment 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 ments display panel
let ments = document.getElementById('customer-ments').innerText; // grab ment 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(ments);
Appreciate the help
Thank you
Share Improve this question edited Dec 17, 2020 at 13:11 Liam 29.8k28 gold badges139 silver badges203 bronze badges asked Dec 14, 2020 at 21:53 Alex VirdeeAlex Virdee 1211 silver badge13 bronze badges 4- 5 Can I ask why you want to do this, as opposed to just using a fixed width and letting the browser wrap the text between words? – user5734311 Commented Dec 14, 2020 at 21:56
- Maybe this can help you css-tricks./injecting-line-break – Fabio Lopez Commented Dec 14, 2020 at 21:58
-
1
I strongly suggest you go about doing the CSS way as suggested above, but if you still need to implement it the way you asked for, then replace the last line of javascript with this:
document.getElementById('customer-ments').innerHTML = newLines(ments);
– Parikshith Kedilaya M Commented Dec 14, 2020 at 22:03 -
1
"1234567890123456789012345678901234567890123456789012345678901234567890".replace(/(.{10})/g, '$1<br/>');
– epascarello Commented Dec 14, 2020 at 22:04
5 Answers
Reset to default 6You 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-ments">
Customer ment 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula neque. Aenean urna nisi, rutrum ac neque eu, aliquet aliquam ligula. Customer ment 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 mentsText = document.getElementById('customer-ments').innerText;
document.getElementById("div2").innerHTML = chunk(mentsText, 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 pleted without cutting it
var max = 120; // Number of letters
var str = '<br>'; // Add <br> tag or something else
var wrapEl = document.getElementById('customer-ments');
var w = wrapEl.innerText.split(' ');
var sum = 0;
var p = 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; p = 0; } else { p = sum; l = i + 1; }
}
wrapEl.innerHTML = w.join(' ');
<div id="customer-ments">
Customer ment 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula neque. Aenean urna
nisi, rutrum ac neque eu, aliquet aliquam ligula. Customer ment 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
版权声明:本文标题:html - Vanilla JavaScript append <br> tag after a certain amount of characters in a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744071372a2528549.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论