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.
CodePudding user response:
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.
CodePudding user response:
I'd recommend: data.toString().replace('\r','').split('\n')