Published
Edited
Oct 11, 2022
5 stars
Insert cell
# Break Word Function

I want to write a function where given an index it adds a `<br>` tag at every Ith index in string. If the index is a space we will insert a `<br>`, but if it's in the middle of a string we insert `-<br>`
Insert cell
my_string = "Here's a really really long string that I want to add breaks to at every 20th interval"
Insert cell
Insert cell
insert_break = (str, index) => {
let result = "";
for (let i = 0; i < str.length; i += index) {
let chunk = str.substring(i, i + index);
if (chunk.endsWith(' ')) {
chunk += '<br>';
} else {
chunk += '-<br>';
}
result += chunk;
}
result = result.replace(/-?<br>$/, ''); // remove last `<br>`
return result;
}
Insert cell
renderHtml(insert_break(my_string, 20))
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more