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

95
Visualizações
Why is regex working only if function scoped variable is declared before the local doCount function

I have some sample code at the following link: working sample.

var a = "sd 1234 abc \n";

function removeNewLineCharacter1() {
  doCount(a);

  var _trimNewLineCharsRegExp = /(^[\n\r]+)|([\n\r]+$)/g;

  function doCount(g) {
    var originalLength = g.length;
    g = g.replace(_trimNewLineCharsRegExp, "");
    console.log("original length :" + originalLength + " and final length : " + g.length);
  }
}

function removeNewLineCharacter2() {
  var _trimNewLineCharsRegExp = /(^[\n\r]+)|([\n\r]+$)/g;

  doCount(a);

  function doCount(g) {
    var originalLength = g.length;
    g = g.replace(_trimNewLineCharsRegExp, "");
    console.log("original length :" + originalLength + " and final length : " + g.length);
  }
}
<button id="btn1" onclick="removeNewLineCharacter1(); return false;">Remove new line character(s) 1</button>
<button id="btn1" onclick="removeNewLineCharacter2(); return false;">Remove new line character(s) 2</button>

When I click on the the button that says Remove new line character(s) 1 the new line character is not trimmed from the string a. However, when I click on the button that says Remove new line character(s) 2 then the new line character gets removed. Both these buttons are calling different functions when they are clicked, but the difference between these called functions is simply that the regex expression variable _trimNewLineCharsRegExp is declared before doCount local scoped function in the called function that works.

Question

Why is the new line character not being removed by the first button onclick function?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

Variables declared with var are hoisted, so it doesn't matter when it is declared.

The key here is when it is assigned a value.

In the first example, it is undefined, then you call the function (passing undefined to g.replace), then you give it a value.

In the second example, you give it a value before calling the function (so you pass /(^[\n\r]+)|([\n\r]+$)/g to g.replace).

about 4 years ago · Santiago Gelvez Relatório

0

Variables defined with var get hoisted. This means that the declaration is moved a the top of the function. But they get initialized where you assign them a value.

In your case, in one instance you are initializing the variable before calling doCount and in another after.

This means that inside removeNewLineCharacter1 doCount gets executed with a value of undefined for _trimNewLineCharsRegExp. This is where the difference comes from.

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