Reputation: 11
I'm using let names = fs.readFileSync(namefile).toString().split("\n")
. Whenever I do
for(const name of names) {
console.log(`First Name: ${name.split(" ")[0]} Last Name: ${name.split(" ")[1]}
}
the last name part always has \r
at the end, how do I make it not add the \r
?
Upvotes: 1
Views: 2846
Reputation: 4419
fs.readFileSync
doesn't add anything to the end of lines,
instead the file that you're trying to read is using CRLF
line endings, meaning that each line ends with the \r\n
sequence.
Really your file looks something like this:
line1\r\nline2\r\nline3\r\n
But your text editor will hide these characters from you.
This is IDE specific but if you use Visual Studio Code you can find the option in the bottom right.
Clicking on it will allow you to change to LF
line endings, a sequence where lines are followed by a single \n
character.
\r
charactersFollowing on from your example we can use .replace
to remove any \r
characters.
let names = fs.readFileSync(namefile)
.toString()
.replace(/\r/g, "")
.split("\n")
Upvotes: 8