I have a text with new lines on javascript. I used text.split('\\n')
to split it into an array.
So what I have now is this:
[
'Hello world',
'',
'',
'This is the first line',
'',
'This is the second line',
'',
'',
'',
'',
'This is the last line'
]
I want each new line to be 5px of margin, so I want to convert it to this:
<p style={{ marginBottom: '10px' }}>Hello world</p>
<p style={{ marginBottom: '5px' }}>This is the first line</p>
<p style={{ marginBottom: '20px' }}>This is the second line</p>
<p>This is the last line</p>
I think I can write a function to do it like this:
<p>
, then reset the accumulator to 0.Maybe there's a better way of doing it?
Using js to set styles can be tricky also by your method it would lead to complex calculations .. Leave to css and use html tags !
See example =>
HTML
<div id="main"></div>
CSS
.spacer {
display: block;
height: 5px; /* Adjust the margin by changing height */
}
JS
const main = document.querySelector('#main')
let array = [
'Hello world',
'',
'',
'This is the first line',
'',
'This is the second line',
'',
'',
'',
'',
'This is the last line'
]
let html = "";
array.forEach(val => val === "" ? html += "<div class='spacer'></div>": html += `<p> ${val} </p>`)
main.innerHTML = html;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.