奇怪的JavaScript换行符分割行为

3

我有一个从远程检索的文本文件,我希望按照两个换行符(\n)分割它。例如,流行的赞美诗《万物亮丽莫名奇妙》

All Things Bright And Beautiful
Cecil F. Alexander

All things bright and beautiful,
All creatures great and small,
All things wise and wonderful,
The Lord God made them all. 

Each little flower that opens,
Each little bird that sings,
He made their glowing colours,
He made their tiny wings.

The purple-headed mountain,
The river running by,
The sunset and the morning,
That brightens up the sky;

The cold wind in the winter,
The pleasant summer sun,
The ripe fruits in the garden,
He made them every one;

The tall trees in the greenwood,
The meadows for our play,
The rushes by the water,
To gather every day;

He gave us eyes to see them,
And lips that we might tell
How great is God Almighty,
Who has made all things well.

在 TextMate 中打开不可见字符显示,可以看到诗句之间有两个换行符。目前为止一切正常。当我将这段文字复制粘贴到 irb 中时,一切都完全正常:

ruby-1.8.7-p334 :034 > content.split "\n\n"
 => ["All Things Bright And Beautiful\nCecil F. Alexander", "All things bright and beautiful,\nAll creatures great and small,\nAll things wise and wonderful,\nThe Lord God made them all. ", "Each little flower that opens,\nEach little bird that sings,\nHe made their glowing colours,\nHe made their tiny wings.", "The purple-headed mountain,\nThe river running by,\nThe sunset and the morning,\nThat brightens up the sky;", "The cold wind in the winter,\nThe pleasant summer sun,\nThe ripe fruits in the garden,\nHe made them every one;", "The tall trees in the greenwood,\nThe meadows for our play,\nThe rushes by the water,\nTo gather every day;", "He gave us eyes to see them,\nAnd lips that we might tell\nHow great is God Almighty,\nWho has made all things well."] 
ruby-1.8.7-p334 :035 > 

问题出现在我开始使用 JavaScript 的时候。在控制台中:
如果我按 一个 \n 分割,它完全正常工作。我已经尝试使用回车符、换行符、将正则表达式传递为分隔符,但什么都没有用。我无法澄清这种行为。
非常感谢任何帮助。

1
"回车符" \n ... "换行符" \r. - Incognito
1
数据是如何进入元素的?也许有些东西在缩进HTML代码,导致\n\n变成了\n \n - jpa
1
它可以工作:http://jsfiddle.net/7Xe7q/将诗歌复制到其中并单击拆分。然后检查控制台。 - Joseph Marikle
2个回答

4
JavaScript中的split与Ruby相同。由于您将文本导入脚本的方式不同,所以最有可能是`\n`被转换成了其他字符。
请使用以下代码进行操作:`this.element_content.split('')`。
var s = this.element_content;
var chars = [];
for(i=0; i<s.length; i++){ chars.push(s.charAt(i)); }
console.log(chars)

将您的字符串转换为字符数组并检查在换行符中实际使用了什么。

当将其分成单个字符时,我可以看到一个换行符,然后是一个空字符串(没有空格,只有""),然后又是一个换行符。我不知道如何将其“转换”为split()调用。 - Jamie Rumbelow
其中一条评论提到可能是使用 split('\n \n')。我刚刚检查了一下,这可能就是你想要的。 (事后看来,在这种情况下,使用 split('') 转换成数组可能不是一个好方法。一个简单的 for 循环和 .charAt 方法可能更精确一些) - hugomg
非常感谢您迄今为止的帮助。不幸的是,split('\n \n') 没有解决任何问题。我也尝试过双引号(虽然那应该没有关系)。这真的是一个令人困惑的问题! - Jamie Rumbelow
很可能是回车符的问题。也许使用正则表达式来删除所有回车符会有帮助? - beatgammit
@Jamie Rumbelow:你是否使用更准确的转换来检查空格中使用了哪些字符? - hugomg
最终我进行了全局替换,将所有隐藏的空格字符替换掉,结果发现一直都是\r\n。虽然不知道为什么,但是问题解决了!感谢大家的帮助! - Jamie Rumbelow

2

尝试使用m来处理多行文本,将this.element_content.split(/[\n\r]{1,2}/m)分割。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接