奇怪的JavaScript换行分裂行为

时间:2011-09-18 14:26:33

标签: javascript string split newline coffeescript

所以,我有一个远程检索的文本文档,我希望用两个换行符(\ n)来拆分。例如,流行的赞美诗 All Things Bright And Beautiful

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的那一刻。在控制台中:

enter image description here

如果我按一个分开,它的效果绝对正常。我尝试过使用回车,换行符,将正则表达式作为分隔符传递,似乎没有任何工作。我无法揭开这种行为的神秘面纱。

任何帮助都将受到全面的赞赏。

2 个答案:

答案 0 :(得分:4)

Javascript的分割与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)

将您的字符串转换为字符数组,并检查换行符中实际使用的内容。

答案 1 :(得分:2)

尝试this.element_content.split(/[\n\r]{1,2}/m)使用m进行多行