admin管理员组

文章数量:1310441

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 plete 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

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 plete 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

Share Improve this question edited Mar 8, 2019 at 18:42 Nafees Anwar 6,6083 gold badges27 silver badges44 bronze badges asked Mar 8, 2019 at 18:31 user2032090user2032090 971 gold badge2 silver badges7 bronze badges 2
  • 3 I love the great variety of reasonable answers already posted! – Scott Sauyet Commented Mar 8, 2019 at 18:45
  • According to a quick test, index of is way faster than regex codepen.io/ArthyFiciel/pen/pYPMgL – Arthur Commented Mar 8, 2019 at 19:11
Add a ment  | 

5 Answers 5

Reset to default 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))

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))

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)
)

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

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))

本文标签: Truncate string after the cutting word in JavascriptStack Overflow