2011-09-18 118 views
3

所以,我有一个远程检索的文本文件,我想分裂两个换行符(\ n)字符。例如,受欢迎的赞美诗All Things Bright And Beautiful奇怪的JavaScript新行分裂行为

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与invisibles上显示我在诗句之间的两个换行符。到现在为止还挺好。当我复制并粘贴到这个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

如果我分裂由一个\ n它工作绝对没问题。我试过使用回车符,换行符,传递正则表达式作为分隔符,似乎没有任何工作。我只是无法揭开这种行为的神秘面纱。

任何帮助将得到彻底赞赏。

+1

“回车” \ n ... “换行” \ r。 – Incognito

+1

数据如何进入元素?也许有东西缩进HTML代码,导致'\ n \ n'变成'\ n \ n' – jpa

+1

它确实有效:http://jsfiddle.net/7Xe7q/ c/p那里的诗,然后点击split。然后检查控制台。 –

回答

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) 

将字符串转换成字符数组,并检查什么是真正正的换行符使用。

+0

当分割成单个字符时,我可以看到一个换行符,然后是一个空字符串(没有空格,只是“”),然后是另一个换行符。我不知道如何将它转换为split()调用。 –

+0

其中一个评论提到它可能是'split('\ n \ n')'。我刚刚检查过,这可能是你想要的。 (事后看来,split('')在这种情况下可能不是一种转换为数组的好方法。一个简单的for循环和.charAt方法可能会更精确) – hugomg

+0

非常感谢你的帮助,迄今为止。不幸的是,split('\ n \ n')'没有解决任何问题。我也试着用双引号(不是那应该重要)。这真的是相当头疼的人! –

2

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