4

I want to truncate a string after certain characters length in javascript. When the character length is reached then string should not be cut in the middle of the word rather it should complete the word and then truncate the string. What I have tried uptil now cuts the string before the cutting word. I want to include the cutting word in returned string. Here is my code:

function truncateString(yourString, maxLength) {
  var trimmedString = yourString.substr(0, maxLength);
  trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
  return trimmedString;
}

now when I call this function on with following parameters:

truncateString('The quick brown fox jumps over the lazy dog',6)

The output is 'The' rather than 'The quick.

Please point out what I need to change. Thanks

Nafees Anwar
  • 6,324
  • 2
  • 23
  • 42
user2032090
  • 97
  • 1
  • 2
  • 7

5 Answers5

6

You can search for the index of immediate space after the maxLength by using the second parameter of indexOf

function truncateString(yourString, maxLength) {
  // get the index of space after maxLength
  const index = yourString.indexOf(" ", maxLength);
  return index === -1 ? yourString : yourString.substring(0, index)
}

const str = 'The quick brown fox jumps over the lazy dog';

console.log(truncateString(str,6))
console.log(truncateString(str,10))
console.log(truncateString(str,100))
adiga
  • 34,372
  • 9
  • 61
  • 83
  • Humm.. Didn't know this feature. Your answer may be better than mine :p But you should test than `index != -1` before using `substring` – Arthur Mar 08 '19 at 18:40
2

One alternative is using regex.

You can build a regex pattern based on the value passed to function.

^.{${value}}.*?\\b
       |     |_____________ expression to get value upto next word boundry
       |
       |___________________ Value passed to function

let trmStr = (input,value) => {
  let reg = `^.{${value}}.*?\\b`
  let regex = new RegExp(reg)
  return input.match(regex)
}

console.log(trmStr('The quick brown fox jumps over the lazy dog', 6))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

So long as the maxLength is on a non-white space character, increase it.

function truncateString(yourString, maxLength) {
  while (maxLength < yourString.length && yourString[maxLength] != ' '){
    maxLength++;
  }
  
  return yourString.substr(0, maxLength);
}

console.log(
  truncateString('The quick brown fox jumps over the lazy dog',6)
)
Taplar
  • 24,788
  • 4
  • 22
  • 35
1

In your example:

trimmedString // "The qu"
trimmedString.length // 6
trimmedString.lastIndexOf(" ") // 3
Math.min(trimmedString.length, trimmedString.lastIndexOf(" ") // 3

So currently you go to the space that occurred before the current word, instead of the space after it.


Here's a potential solution:

  1. Find the endIndex by finding the index of the first space (" ") that occurs on or after the maxLength (see indexOf)
  2. Return the substring ending just before endIndex
JBallin
  • 8,481
  • 4
  • 46
  • 51
0

You can doing it with reduce function. Add a word while total lenght isn't reach.

function truncateString(yourString,maxLength)
{
   return yourString.split(' ').reduce((acc, str) => { return (acc.length < maxLength) ? acc + " " + str : acc  }, '')
}
console.log(truncateString('The quick brown fox jumps over the lazy dog',6))
Arthur
  • 4,870
  • 3
  • 32
  • 57
  • One minor disadvantage of this is that it will continue to iterate long after the length has been reached. Probably not a big deal, but you never know. – Scott Sauyet Mar 08 '19 at 18:48
  • It was my concern about my answer, I think adiga's one is better. And I was looking to a solution to stop reduce function (break or return will not work here :/) – Arthur Mar 08 '19 at 18:49
  • In case of interest : https://stackoverflow.com/questions/36144406/how-to-break-on-reduce-method – Arthur Mar 08 '19 at 18:58
  • Very interesting. I would never use the accepted solution there, but I also would not have thought it at all possible. – Scott Sauyet Mar 08 '19 at 19:16