stringgotruncate

How can I elliptically truncate text in golang?


I'd like to be able to cleanly cut a paragraph larger than certain number of characters without cutting a word in the middle.

So for example this:

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.

Should become:

It is a long established fact that a reader will be distracted by the readable content ...

Here is the function that I came up with:

 func truncateText(s string, max int) string {
    if len(s) > max {
        r := 0
        for i := range s {
            r++
            if r > max {
                return s[:i]
            }
        }
    }
    return s
}

But it just brutally cuts the text. I'm wondering how can I modify (or replace it with a better solution) in order to cut the text elliptically?


Solution

  • Slicing strings can be problematic because slicing works with bytes, not runes. Range, however, works with runes:

    lastSpaceIx:=-1
    len:=0
    for i,r:=range str {
      if unicode.IsSpace(r) {
         lastSpaceIx=i
      }
      len++
      if len>=max {
        if lastSpaceIx!=-1 {
            return str[:lastSpaceIx]+"..."
        }
        // If here, string is longer than max, but has no spaces
      }
    }
    // If here, string is shorter than max