Search code examples
reactjsstringsubstring

display a string in react


I have a string as shown below which I want to truncate it after a particular character limit and display an ellipsis.

"This is a long string"

On truncation, I want the string to display something like this:

This is a long (...)

or

This is a (...)

or

This is (...)

The above examples don't cut the words. What I don't want is:

This is a lon (...)

or

This is a long s (...)

The above examples don't work.

I am using the following function in react to truncate a string. The problem with the function is that it sometimes cut the words. The value of length I am using is 175. For 175 character limit, sometimes it cut the words and sometimes it doesn't.

export const wordsTruncate = (words, length) => {
    const j = words.split('');
    let result = j.filter((z, a) => a <= (length - 1));

    return result.join("");
}

I am wondering what changes I need to make in the function above so that it doesn't cut the words as shown in the examples above.


Solution

  • Try this. hope this works for you.

    const wordsTruncate = (words, length) => {
      words = words.trim(); //you need to decied wheather you do this or not
      length -= 6; // because ' (...)'.length === 6
      if (length >= words.length) return words;
    
      let oldResult = /\s/.test(words.charAt(length));
      for (let i = length - 1; i > -1; i--) {
        const currentRusult = /\s/.test(words.charAt(i))
    
        //check if oldresult is white space and current is not.
        //which means current character is end of word
        if (oldResult && !currentRusult) {
          return `${words.substr(0, i + 1)} (...)`;
        }
        oldResult = currentRusult;
      }
      // you need to decide whether you will just return truncated or original
      // in case you want original just return word
      return '(...)';
    }
    
    console.log(wordsTruncate('This is long text blabla blasdf test.', 32));
    console.log(wordsTruncate('This is', 22));
    console.log(wordsTruncate('This is', 7));
    console.log(wordsTruncate('This is', 13));
    console.log(wordsTruncate('This is ', 13));
    console.log(wordsTruncate('Thisadsfasdfasdfasdfasdf', 22));

    So length should be final length of truncated string.

    eg: 'This is long text blabla (...)'.length