简体   繁体   English

JavaScript —在字符串的每个换行符处插入“ \\ r \\ n”

[英]JavaScript — insert “\r\n” at every line break in string

I'm trying to use this CSV parsing library to parse my CSV, but it seems that this library needs "\\r\\n\\" to be at the end of every row. 我正在尝试使用此CSV解析库来解析我的CSV,但似乎该库需要“ \\ r \\ n \\”位于每一行的末尾。

Right now, my CSV looks like this: 现在,我的CSV如下所示:

Bob, Smith, Cats,
Annie, Johnson, Dogs

How do I add the string "\\r\\n\\" right after "Cats" and "Dogs"? 如何在“猫”和“狗”之后添加字符串“ \\ r \\ n \\”? Or is this unnecessary? 还是这是不必要的? Thanks! 谢谢!

Check what works for your environment! 检查什么适合您的环境!

You could change the default '\\r\\n' to '\\n' like below: 您可以将默认的'\\r\\n'更改为'\\n'如下所示:

var csv = new CSV(data, { line: '\n' });

Hope this helps! 希望这可以帮助!

You may try something like this: 您可以尝试如下操作:

var text = "Box, Smith, Cats\nAnnie, Johnson, Dogs";
text = text.split( "\n" ).join( "\r\n" );

JsFiddle JsFiddle

In this case, the documentation indeed says you can simply specify the line characters yourself with the line option as already pointed out in the other answer. 在这种情况下,文档确实说您可以简单地使用line选项指定行字符,如其他答案中已经指出的那样。

Just providing some additional info on this: 只是提供一些其他信息:

\\r stands for carriage return \\ r代表回车
\\n stands for line feed (newline) \\ n代表换行(换行符)
Depending on which program you used to generate or manually write the CSV file, when you hit Enter this will produce either \\n or \\r\\n 根据您用于生成或手动写入CSV文件的程序,当您按Enter键时,将生成\\n\\r\\n

You can 'pre-cure' this with a text editor like Notepad++, Sublime Text, Brackets, etc. which have a regex replace feature. 您可以使用文本编辑器(例如Notepad ++,Sublime Text,括号等)进行“预固化”,这些编辑器具有regex替换功能。 ( Ctrl + H to bring it up in most cases). (在大多数情况下, 按Ctrl + H即可)。 Most notably, Notepad++ allows you to see all characters in the View menu (\\r will show up as a block with CR & \\n will show up as a block with LN). 最值得注意的是,Notepad ++允许您在“视图”菜单中查看所有字符 (\\ r将显示为带有CR的块,\\ n将显示为带有LN的块)。

Simply check the Regex checkbox or icon and replace all \\n with \\r\\n or vice versa. 只需选中Regex复选框或图标,然后将所有\\n替换为\\r\\n ,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM