After we open the .txt file in the website, we often add the obtained text to the element, but Javascript will automatically ignore the \r\n in the file. This post will cover : ① How to use <input> to select files? ② How to read .txt file using Reader()? ③ How to keep \r\n effect of .txt file?
Keywords: Javascript , Reader() , read .txt , \r\n , keep \r\n effect.
HTML
Add a <input> element to the web page, and then listen to the change event of <input>, you can open the file explorer from the website and select a file.

original text in file

wrong read without \r\n

right read with \r\n
Keep \r\n
Listen for the change of <input> in the window.onload() function, then verify the file type and only open the .txt file. After opening the file, process \r and \n through processBlankLine(), mainly by replacing ‘\r\n’, ‘\n’, ‘\r’ with the special string ‘special_str_for_split’, and then splitting the original text with ‘special_str_for_split’ , finally merge the resulting arrays, and the effect of \r\n can be maintained.
code of keeping \r\n
When reading text from a .txt file and setting innerHTML for <p>, directly using p.innerHTML =text cannot display the \r\n effect correctly. At this time, the string needs to be split, and the ‘\n\r’, ‘\n’ , ‘\r’ are need correctly replaced with <br>. Although it is easy to replace ‘\n\r’ , ‘\n’ , ‘\r’ with <br> directly, but in Vue, if you want to assign each paragraph of text to <span> through a loop , the way to split to get the correct paragraph array in this post is better.