Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

314
Visualizações
Shorten text after 50 characters but only after the current word

I need to shorten text after 50 characters but if the 50th char is at the middle of a word - cut only after the word and not before.

example text: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars)

expected output: Contrary to popular belief, Lorem Ipsum is not simply (54 chars)

I was trying this: text.substr(0,50).lastIndexOf(' ')); - not good for me cause it cuts of the "simply" and I want the simply to be at the shorten text. Thanks for the help!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If the phrase length is less than the limit, return the phrase; else, set the slice index to the limit and scan until you find a word boundary and slice the phrase.

const clip = (phrase, limit) => {
  if (phrase.length <= limit) return phrase;
  let sliceIndex = limit;
  while (sliceIndex < phrase.length && /\b/.test(phrase[sliceIndex])) sliceIndex++;
  return phrase.slice(0, sliceIndex);
};

const input = "Contrary to popular belief, Lorem Ipsum is not simply text";

const expected = "Contrary to popular belief, Lorem Ipsum is not simply";

const actual = clip(input, 50);

console.log(actual === expected); // true

about 4 years ago · Juan Pablo Isaza Relatório

0

You were close with the substring & indexOf. If you look for a space after the first 50 characters it will work. Then there is an edge case where the string is longer then 50 characters and no space.

const shortener = (str) => {
  const offset = str.substring(50).indexOf(' '); 
  return offset !== -1   ? str.substring(0,50 + offset) + '...' : 
         str.length > 50 ? str + '...' : str;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Regular expression can help you with it.
The idea is to find at least 50 symbols that finishes with word boundary \b

let text = 'Contrary to popular belief, Lorem Ipsum is not simply text';
let shortetedText = text.match(/.{50,}?(?=\b)/)[0];
console.log(shortetedText);

UPD:
If you want to create a function that shorten your text if it's longer than 50 symbols we can create a function that do it instead of you.

let short = text => text.length > 50 ? text.match(/.{50,}?(?=\b)/)[0]: text;  

Then just use it like that:

let longText = 'Contrary to popular belief, Lorem Ipsum is not simply text';
let shortText = 'Lorem ipsum';
console.log(short(longText)); //will shorten text
console.log(short(shortText)); //will leave text as it is bcoz it's shorter than 50 symbols
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda