我努力寻找解决问题的方法,尽管分享它会很棒。这是问题所在:
我有一个文本,它可能包含任何类型的标点符号。我想把它分成两部分:
以下是一些例子:
str = "one two, three, quatro 5! : six sept ocho nine 10!"
splitAfterXWords(str, 2)
// ["one two,", "three, quatro 5! : six sept ocho nine 10!"]
splitAfterXWords(str, 5)
// ["one two, three, quatro 5!", " : six sept ocho nine 10!"]
splitAfterXWords(str, 20)
// ["one two, three, quatro 5! : six sept ocho nine 10!", ""]
splitAfterXWords(str, 6)
// ["one two, three, quatro 5! : six", " sept ocho nine 10!"]
答案 0 :(得分:3)
这是一个完成工作的功能:
function splitAfterXWords(to_split, words){
regex = new RegExp("(([\\s;:!,.?\"'’]*[^\\s]+){" + words + "})(.*)")
result = regex.exec(to_split)
return result ? [result[1], to_split.substr(result[1].length)] : [to_split, '']
}
您可以在this fiddle上看到它。
欢迎改进和评论!
答案 1 :(得分:3)
以下是我尝试从特定句子中获取n
个字词:
var regexp = /\s*\S+\/;
function truncateToNWords(s, n) {
var l=0;
if (s == null || n<= 0) return l;
for (var i=0; i<n && (match = regexp.exec(s)) != null; i++) {
s = s.substring(match[0].length);
l += match[0].length;
}
return l;
}
// your sentence
var s = "one two, three, quatro 5!: six sept ocho nine 10!";
l = truncateToNWords(s, 2);
console.log([s.substring(0, l), s.substring(l)]);
l = truncateToNWords(s, 5);
console.log([s.substring(0, l), s.substring(l)]);
l = truncateToNWords(s, 6);
console.log([s.substring(0, l), s.substring(l)]);
l = truncateToNWords(s, 20);
console.log([s.substring(0, l), s.substring(l)]);
["one two,", " three, quatro 5!: six sept ocho nine 10!"]
["one two, three, quatro 5!:", " six sept ocho nine 10!"]
["one two, three, quatro 5!: six", " sept ocho nine 10!"]
["one two, three, quatro 5!: six sept ocho nine 10!", ""]