Причудливое поведение расщепления новой строки JavaScript - PullRequest
3 голосов
/ 18 сентября 2011

Итак, у меня есть удаленный текстовый документ, который я хочу разделить на два символа новой строки (\ 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

Если я разделю на one \ n , это будет работать абсолютно нормально.Я пытался использовать возврат каретки, новые строки, пропуская регулярное выражение в качестве разделителя, и ничего, похоже, не работает.Я просто не могу демистифицировать это поведение.

Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

4 голосов
/ 18 сентября 2011

Сплит 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)

для преобразованиясвою строку в массив символов и проверьте, что на самом деле используется в разрывах строк.

2 голосов
/ 18 сентября 2011

Попробуйте, this.element_content.split(/[\n\r]{1,2}/m), используя m для мультилинии

...