1

I have a quite problematic task, I'd like to calculate the width of the widest word in my div, so I can set a min-width with javascript on a resizable div.

I tried working on something, I managed to get the longest word, unfortunately not the widest and I also failed to get his width.

Fiddle : https://jsfiddle.net/Lindow/oayddb8w/3/

JavaScript :

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length; i++) {
        if (longest < str[i].length) {
            longest = str[i].length;
            word = str[i];
        }
    }
    return word;
}

var test = document.getElementById("Test");
var longest_word = longestWord(test.innerHTML); // test.innerHTML == 'dofkdspakdasdsakd,'
var width = (longest_word.clientWidth + 1) + "px"; // 'NaNpx'
alert(longest_word);

HTML :

<div id="Test">
  abcdefghijklmn, opqrstuvwxyzAB
  ddoafkpdsfk, 
  dsapdlasèd. CDEFGHIJKLMNO,
  dofkdspakdasdsakd, PQRSTUVWXYZ
</div>

Any suggestion ? The issue here is not to get the width of all the words, but just the widest word in a bunch of text, which change the problematic.


UPDATE :

This post helped me : Find the width of the widest word in the html block

I have to put every word in <span> tag and check through them which one is the widest according their fontFamily and fontSize.

Horai Nuri
  • 5,358
  • 16
  • 75
  • 127
  • 1
    Are you sure you want the width of the longest word and not the widest word? "OOO" could be wider than "iiiii". – Paul May 30 '17 at 22:48
  • @Paulpro Haven't thought about that, but I'd like to get the one with the biggest number of px, I'll edit that right away – Horai Nuri May 30 '17 at 22:49
  • @MichałDąbrowski Absolutely not, since it's a word on a div and not a all the div's content – Horai Nuri May 30 '17 at 22:51
  • 3
    It is, actually, the same since you're going to do the same thing (probably), which is to put each word into a `span`, get the `width()` of the element, and whichever word was the widest in that set, that's the widest width word. Whether the string has spaces in it or not is irrelevant. – Jared Farrish May 30 '17 at 22:53
  • @rlemon Absolutely not, since it's a word on a div and not a all the div's content. – Horai Nuri May 30 '17 at 22:55
  • @JaredFarrish Best answer so far, I'll try this. – Horai Nuri May 30 '17 at 23:01
  • 1
    @Lindow - Here's a rough approximation of what I'm talking about (it could be coded better): https://jsfiddle.net/oayddb8w/4/ – Jared Farrish May 30 '17 at 23:09
  • @JaredFarrish This seems perfect, you can publish it as answer so I can mark it as solution. – Horai Nuri May 30 '17 at 23:12
  • I wonder when StackOverflow database is going to break by questions, which answer to can be easily found already in the same database? – Michał Dąbrowski May 30 '17 at 23:12
  • @Lindow - It's the same (generally) as the other answer, so I closed as duplicate. If you'd like, upvote the comment so others may see it easier if you want. – Jared Farrish May 30 '17 at 23:14
  • @JaredFarrish I see, the fact that we're measuring the width by widest and not longest + the fact that it's one word in a bunch of others didn't seem a duplicate for me. Thanks – Horai Nuri May 30 '17 at 23:16

3 Answers3

1

It's a strange need, so there is no "clean" option. However if you really want to do that, you can follow these steps :

  1. Measure the size of each letter in hidden span, one for each. You can have that stored or calculate it in live, per browser since fonts aren't interpreted similarly by each browser renderer.
  2. Split the words in your text (by space I guess)
  3. Calculate the width of each word depending on which letters it contains including an average space width between letters. This won't be perfectly accurate but it should be "right enough".
  4. Now you just have to order your sum results in descending order and get the first one to know which word is displayed as the longest one (and get its width in pixels).
Ivan Gabriele
  • 6,433
  • 5
  • 39
  • 60
0

You can place the words into seperate hidden divs and then measure them in a loop until you get the largest one.

Example Here: Calculate text width with JavaScript

JJWALLACE
  • 51
  • 9
0

iiiiiiiiii

WWWWWWWWWW

Your approach is a little flawed. See the 10 i characters above? See the 10 W characters below it? Their character counts are the same, but obviously the W characters have a greater horizontal span in pixels. Your approach will only work correctly with a monospaced (fixed width) font like Courier.

You might take a few other approaches:

  1. (Easiest) Settle on a fixed width for the div, and don't worry about the width.
  2. Settle on a fixed width for the div. Use the text-overflow CSS attribute, and specify 'ellipsis'.
  3. Iterate through ALL words. Place the characters of each word into an empty div, get its ACTUAL pixel width (not characters), and note which one is the widest. Set your div size according to the result.
Xavier J
  • 4,326
  • 1
  • 14
  • 25
  • https://stackoverflow.com/questions/12501171/find-the-width-of-the-widest-word-in-the-html-block this post will solve the issue of the widest width, since now you pointed that out I know that some words will have a different font site than others. – Horai Nuri May 30 '17 at 23:00