Truncate string after the cutting word in Javascript

问题: 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 rath...

问题:

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


回答1:

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


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


回答3:

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


回答4:

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

回答5:

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

  • 发表于 2019-03-10 09:07
  • 阅读 ( 252 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除