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

203
Visualizações
Targeting a whitespace before the linebreak with Regex

I want to strip comments after the symbol and the whitespace at the end of lines so my code is following like this

function solution(input, markers) {
   let regexp = new RegExp("["+ markers.join('') + "].*","gi")
   let removeWhiteSpace = input.replace(regexp,"")
   return removeWhiteSpace.replace(/\s+$/g,"")
};

I have a string like the following

console.log(solution("apples, plums % and bananas\npears\noranges !applesauce",["%", "!"]))

I have trouble in targeting the whitespace after the "plums" without affecting the other white spaces. What can I improve in this regex to target that whitespace.

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

0

What your code does is it matches everything after '%' or '!' and then replace whitespaces at the end of the string. If you are trying to remove the symbols in markers and strip any extra whitespace at the end of the string then you can do that in one line of code:

let regex = /(?:[%!]+\s*|\s*$)/gm
input.replace(regex, "")

regex: /(?:[%!]+\s*|\s*$)/gm

(?:          Non capture group
  [%!]+\s*   zero or more spaces that follow one or more symbols (from marker var) 
  |          OR
   \s*$       zero or more spaces at the end of the input string
)
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