JSFiddle - React, Tailwind, and code Playground
HTML
<div id="myDiv">
</div>
JavaScript
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
function splitValue(value, index) {
return value.substring(0, index) + "," + value.substring(index);
}
function evenBreak(myString) {
var count = (myString.match(/ /g) || []).length; //How many spaces are there
var middle = Math.ceil(count/2); //Find the middle one
var middleIndex = nth_occurrence(myString, " ", middle); //Get the index of the middle one
var splitString = splitValue(myString, middleIndex).split(","); //Split the string into two pieces at our middle
myString = splitString[0] + "<br>" + splitString[1].substring(1); //Put it back together with a line break between
return myString;
}
document.getElementById("myDiv").innerHTML = evenBreak("This is a long piece of text that will hopefully get split up in the center!");