JSFiddle - React, Tailwind, and code Playground
by stefek99
HTML
<input type="text" id="split" style="width:600px" value="Split me because I'm so long and I won't fit in a single line"></input>
<input type="button" value="split!"></input>
<br>
<span id="result"></span>
<span id="measure" style="visibility:hidden;"></span>
JavaScript
var html = document.getElementById("measure");
var GetTextSize = function (sText)
{
if(sText == null)
{
return 0;
}
else
{
html.innerHTML = sText;
return html.offsetWidth
}
};
$("input[type=button]").click(function() {
var text = $("#split").val();
var result = "";
if (text.length < 32) {
result = text;
}
else {
var nOptimalSplitDifference = Number.MAX_VALUE;
var nOptimalSplitIndex = text.length;
var nSplitIndex = text.indexOf(' ');
while(nSplitIndex != -1) {
nSplitIndex = text.indexOf(' ', nSplitIndex + 1);
var sPartOne = text.substring(0, nSplitIndex);
var sPartTwo = text.substring(nSplitIndex, text.length);
var nPartOne = GetTextSize(sPartOne);
var nPartTwo = GetTextSize(sPartTwo);
var nSplitDifference = Math.abs(nPartTwo - nPartOne);
if (nSplitDifference < nOptimalSplitDifference) {
nOptimalSplitDifference = nSplitDifference;
nOptimalSplitIndex = nSplitIndex;
}
}
result = text.substring(0, nOptimalSplitIndex) + "<br>" + text.substring(nOptimalSplitIndex+1, text.length);
}
$("#result").html(result);
});
$("input[type=button]").click();