How can I get the text length value after truncating through css properties in javascript?

52 Views Asked by At

Text: Value soooo soooo lognnng Value soooo soooo lognnng Value soooo soooo lognnng Value Normal length: 83

Text After Truncate:

Value soooo soooo lognnng...

Truncate length: 28

Question: How to get the text length after truncated?

I tried get length by dom.

But the length is always full. How to get the text length after truncated?

const div = document.querySelector('#txt')
console.log(div.innerText.length)
<div id="txt" style="font-size: 0.9em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
  Value soooo soooo lognnng Value soooo soooo lognnng Value soooo soooo lognnng Value soooo soooo
</div>

1

There are 1 best solutions below

1
Moussa Bistami On

Well that's pretty easy to do let's say you're using a function called truncateMyString to truncate your string you'll need to do the following:

const string = 'very long string'
const truncatedString = truncateMyString(string);
console.log(`the rest of my truncated string length is: ${string.length - truncatedString.length}`);

and that's it, Please let me know if you do not understand something in the code above.