在split(javascript)中包含分隔符 [英] Including separator characters in split (javascript)
本文介绍了在split(javascript)中包含分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个textarea。用户可以写任何东西。
This is a textarea. The user can write anything.
<textarea id="text">First sentence. Second sentence? Third sentence!
Fourth sentence.
Fifth sentence
</textarea>
最后,我必须将所有文本拆分成一个数组。
At the end, i have to split all the text into an array.
var sentences = $('#text').val().split(/\r\n|\r|\n|[.|!|?]\s/gi);
我遇到的问题是,数组项值中不存在分隔符。这是句子返回的内容:
The issue i'm having, is that the separator characters are not present in the array item values. This is what sentences is returning:
["First sentence", "Second sentence", "Third sentence", "Fourth sentence", "Fifth sentence"]
应该是:
["First sentence.", "Second sentence?", "Third sentence!", "", "Fourth sentence.", "", "", "Fifth sentence"]
额外注意事项:
- 最后一句不需要分隔符(可以在任何字符处结束)
- 如果一个句子有多个分隔符char,它也应该包含在数组项中。例如:第二句?? 应该是[...,第二句话??,...]
- last sentence doesn't require a separator character (it can end at any char)
- if a sentence has more than one separator char, it should also be included in the array item. Example: second sentence?? should be [...,"second sentence??",...]
有什么想法吗?任何方法都是受欢迎的(不一定是split()) - 谢谢!
Any ideas? Any approach is welcome (not split() necessarily) - Thanks!
推荐答案
var re = /[^\r\n.!?]+(:?(:?\r\n|[\r\n]|[.!?])+|$)/gi;
("First sentence.. Second sentence?? Third sentence!!\n"+ "Fourth sentence").match(re).map($.trim)
//["First sentence..", "Second sentence??", "Third sentence!!", "Fourth sentence"]
这篇关于在split(javascript)中包含分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文