How to read .txt file by Javascript and keep \r\n effect?

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.

Edit Template

Leave a Reply

Your email address will not be published. Required fields are marked *

Chaoxu Wei

Master student at Tongji University (Writer & Blogger)

Job hunting, both part-time and full-time jobs are accepted. Job recommendation please email me weichaoxu1998@gmail.com, thank you very much!

0
0
Edit Template

“There are many people in the world who want to work hard but can’t, and people who work too hard and are exhausted. Please don’t use your efforts only to chase your own victory, please use them to help others.”

Follow

Contact

libertynlp@163.com

+86-18385537403

Yangpu District, Shanghai