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

292
Visualizações
Use of regex in replace() to join split words in a text

I have this sample sentences in a plain text file (utf-8):

today is an interest-
ing day

the "-" on the first line is followed by only \n (I have already stripped all \r from the file, to deal uniformy with different sources) I would like to wrap the 2 lines in 1 line, because of the "-", meaning that the preceding word has been truncated and is continuing in the next line. To join this kind of lines, what I have tried is something along the lines:

text.replace(/[\n-]/g, "") 

but does not seem to be working. What is the right way to achieve this ?

I would like to be able to deal with both these possible endings (or similar situations you might anticipate):

interest-\n
interest- \n    (possible blanks inserted before \n)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use

text.replace(/\b-\s*\n\b/g, "")
text.replace(/\b-[^\S\r\n]*\n\b/g, "")

See the regex demo. Details:

  • \b - a word boundary
  • - - a hyphen
  • \s* - zero or more whitespaces / [^\S\r\n]* - zero or more horizontal whitespaces (supporting CRLF, CR and LF endings)
  • \n - a newline char
  • \b - a word boundary.

See the JavaScript demo:

console.log( "today is an interest- \ning day".replace(/\b-\s*\n\b/g, "") );
console.log( "today is an interest-\ning day".replace(/\b-\s*\n\b/g, "") );

A Unicode-aware pattern that checks for just letters on both ends can look like text.replace(/(?<=\p{L}\p{M}*)-[^\S\r\n]*\n(?=\p{L})/gu, ""), where (?<=\p{L}\p{M}*) checks for a letter + optional diacritics before - and (?=\p{L}) checks for a letter after a newline. See the regex demo.

about 4 years ago · Juan Pablo Isaza Relatório

0

There are three things wrong in your regex for this use:

  1. You have the new line before the -

  2. The [] means a list of characters to match at least one of them

  3. You need to add \s to match whitespace

So try this:

text.replace(/-\s*\n/g, "") 
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