2

I'm looking for a NPM package that has a function of splitting text based on overflow, more specifically for DOM (I do have the width and height of the container, but I use the Verdana font for the text). For example, given this:

.----------------.
| some text that |
| is too large   | for this div
`----------------´

This should output:

['some text that is too large', 'for this div']

2 Answers 2

3

You can use the "text-fit" NPM package. You can pass the width and height of the container as arguments, along with the font family and font size.

For example:

const textFit = require('text-fit');
 
const text = 'some text that is too large for this div';
 
const containerWidth = 500; const containerHeight = 100;
 
const fontFamily = 'Verdana'; const fontSize = 16;
 
const lines = textFit(text, { containerWidth, containerHeight, fontFamily, fontSize });
 
console.log(lines);
 

This should output:

[ 'some text that is too large', 'for this div' ] 
2
  • textfit looks great! On the other side, line-breaker does not take font into account, if I understand correctly? I would encourage you to post these two solutions as two separate answers, so that voters can vote for one and not the other, for instance, allowing the best answers to bubble up. :-)
    – Nicolas Raoul
    Feb 3 at 8:56
  • Thank you for the recommendation @NicolasRaoul. I updated my answer :)
    – Esha Shah
    Feb 3 at 9:43
1

Another popular NPM package for splitting text based on overflow is "line-breaker NPM package". It provides a function "breakLines()" that takes a string of text and returns an array of lines that can fit within a given width.

For example:

const lineBreaker = require('line-breaker'); 
const text = 'some text that is too large for this div'; 
const width = 500; 
const lines = lineBreaker(text, { width }); 
 
console.log(lines); 

This should output:

[ 'some text that is too large', 'for this div' ] 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.