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

143
Visualizações
String comparison giving wrong result in Javascript

I have below months.txt file in which I have the content:

January
February
March

Then I read the content of the file into an array using below code:

var data=fs.readFileSync('./months.txt');
data=data.toString().split("\n");

Then I send this data array as ejs variable to front end(data array has name of all months):

res.render("file.ejs",{months: data});

I am using the data array in ejs file as:

<select name="month">
<option value="<%= months[0] %>">January</option>
<option value="<%= months[1] %>">February</option>
<option value="<%= months[2] %>">March</option>
</select>

When the chosen item in above dropdown is sent to the server, correct month name is being prined, but now comes the problem. If I select February and do this:

console.log(req.body.month);// prints February
console.log(req.body.month=="February");// prints false

What could be the possible reason behind this? Any suggestions are most welcomed!

EDIT: I just printed data array and it contains this strange elements: [ 'January\r', 'February\r', 'March\r' ] What is this \r? Maybe because of this comparison is returning false.

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

0

On windows computers, linebreaks are denoted by \r\n rather than \n. Using .split('\n') would likely leave in the \r, which is making the comparison false.

Changing your data.toString().split('\n') to data.toString().split('\r\n') would likely remove those.

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd recommend: data.toString().replace('\r','').split('\n')

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