I've got this piece of code and I need to add inside of this.info().Info
a new lines after each 10 words. I'm not very familiar with JavaScript and I'm learning it, but I don't know how to do this. this.info().Info
stores Lorem Ipsum text that is written inside of a field and than saved.
$(this.data()).after('<tr class="info-row"><td colspan="100"><div>' + this.info().Info + '</div></td></tr>');
You can use the mod ( %
) operator, which returns the remainder of x / y
, for that. You can loop through each word to check if the index is divisible by 10 and if it is, add a \n
.
Here is how to do that:
function addNewlineEvery10Lines(text) {
return text.split(" ").map((word, index) => { // get the words in an array and loop through them
if ((index + 1) % 10 === 0) return word + "\n"; // add newline if divisible by 10
return word; // just return word otherwise
}).join(" "); // join the array back up
}
You can now use this function on the info.
$(this.data()).after('<tr class="info-row"><td colspan="100"><div>' + addNewlineEvery10Lines(this.info().Info) + '</div></td></tr>');
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.