Search code examples
javascriptstringecmascript-6ecmascript-5

How to change this substring logic so it will stop when the word is ended closest to the ending value in JS?


I have a string and need to cut it when it longer than 50 characters. The issue is that it cuts the last word.

 showName(name) {
      if (name.length < 50) {
        return name
      } else {
        return name.substring(0, 50) + '...'
      }
    },

How can I do it in a way that last word will be complete?


Solution

  • This is a somewhat naive approach that doesn't handle non-space breaks well, but it might be good enough.

    function showName(name) {
      if (name.length < 50) {
        return name
      } else {
        const short = name.substring(0, 50)
        const shortWords = short.split(/\b/)
        const lastShortWord = shortWords[shortWords.length - 1]
        const words = name.split(/\b/)
        const adjWord = words[shortWords.length - 1]
        if (lastShortWord !== adjWord) {
          return short.substring(0, short.lastIndexOf(' ')) + '...'
        }
        return short + '...'
      }
    }
    
    console.log(showName('A really long name that should span more than 50 characters but not cut in the middle of the last word in the allowed length'))