Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda