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

341
Visualizações
Using negative conditions, how to remove whitespaces except line and paragraph breaks

One simple way to remove whitespaces in my case is to do like this -

<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">

  hello,          how are you 

i'm    fine


And i hope the same from you


</textarea><br>
<button onclick="whitespaces()">Vanish</button> 

<script>
    function whitespaces() {
        var input = document.getElementById("thetext");
        input.value = input.value
            .replace(/\t{1,}/g, "")
            .replace(/\n{3,}/g, '\n\n')
            .replace(/ {1,}/g, ' ')
            .replace(/^ /gm, '')
            .replace(/ $/gm, '')
            .replace(/^\n{1,}/g, '')
            .replace(/\n{1,}$/g, '');
    }
</script>

However I'm trying to achieve the same objective with negative condition. That is by using minus or something like that. As i'm new to js, i'm not familiar with negative conditions. So can anyone tell me how to use negative condition in this case. The code should look something like this -

function whitespaces() {
    var input = document.getElementById("thetext"); 
    input.value = input.value.replace(all whitespaces [\s] minus linebreak [\n] and paragraph breaks [\n\n])
}
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

SOLUTION 1

You can use the following regular expression to match all whitespace characters except newlines.

[^\S\r\n]

That is, not-not-whitespace (the capital S complements) or not-carriage-return or not-newline. Distributing the outer not (i.e., the complementing ^ in the character class) with De Morgan's law, this is equivalent to “whitespace but not carriage return or newline.” Including both \r and \n in the pattern correctly handles all of Unix (LF), classic Mac OS (CR), and DOS-ish (CR LF) newline conventions.

From this stackoverflow answer.

SOLUTION 2

In javascript you can also use a replacer function to check each match and return the replacement string only if it meets certain conditions. The replacer function here checks for each whitespace whether it is a line break.

<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">

  hello,          how are you 

i'm    fine


And i hope the same from you


</textarea><br>
<button onclick="whitespaces()">Vanish</button> 

<script>
    function whitespaces() {
        var input = document.getElementById("thetext");
        var inputVal = input.value;
        inputVal = inputVal.replace(/\s/g, function(match){
            return match === '\n' ? match : '';
        });
        input.value = inputVal;     
    }
</script>

SOLUTION 3

Another possible solution is to first replace all the paragraph breaks and line breaks by some bogus text (without whitespaces). Then do the whitespace replacement. After that convert the bogus texts back to paragraph and line breaks. (Note that since paragraphs are double line breaks, you do not need the line with the paragraph break replacement.)

<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">

  hello,          how are you 

i'm    fine


And i hope the same from you


</textarea><br>
<button onclick="whitespaces()">Vanish</button> 

<script>
    function whitespaces() {
        var input = document.getElementById("thetext");
        var inputVal = input.value;
        inputVal = inputVal.replace(/\n\n/g, "somebogustextforparagraphbreaks");
        inputVal = inputVal.replace(/\n/g, "somebogustextforlinebreaks");
        inputVal = inputVal.replace(/\s{1,}/g, "");
        inputVal = inputVal.replace(/somebogustextforparagraphbreaks/g, "\n\n");
        inputVal = inputVal.replace(/somebogustextforlinebreaks/g, "\n");
        input.value = inputVal;     
    }
</script>

about 4 years ago · Santiago Trujillo 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