Split a string in to pieces based on its pixels using Javascript
https://stackoverflow.com/questions/48669297/split-a-string-in-to-pieces-based-on-its-pixels-using-javascript/48669668#48669668
by Yunus Gaziev
JavaScript
function getWidth(pText, pFontSize, pStyle) {
var lDiv = document.createElement('div');
document.body.appendChild(lDiv);
if (pStyle != null) {
lDiv.style = pStyle;
}
lDiv.style.fontSize = "" + pFontSize + "px";
lDiv.style.position = "absolute";
lDiv.style.left = -1000;
lDiv.style.top = -1000;
lDiv.innerHTML = pText;
const width = lDiv.clientWidth;
document.body.removeChild(lDiv);
lDiv = null;
return width;
}
function splitThroughPixel(string, width, size, style){
const words = string.split(' ');
const response = [];
let current = '';
for(let i=0; i<words.length; i++){
const word = words[i];
const temp = current + (current == '' ? '' : ' ') + word;
if(getWidth(temp, size, style) > width){
response.push(current.trim());
current = '';
}else{
current = temp;
}
}
return response;
}
const myString = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s";
console.log(splitThroughPixel(myString, 200, 14));