被宠坏了,你是。我只是想我会再添加一个选项,并同时回答您的第二个问题:
var mytest = "lorem ipsum dolor sit amet consectetur adipisicing";
var newtext = mytest.replace(/(\w+\W+\w+)\W+/ig,"$1\n");
alert(newtext);
result:
lorem ipsum
dolor sit
amet consectetur
adipisicing
注意 - 最后一个词('adipisicing')不匹配,所以没有被替换。它就在最后(并且没有尾随\n
)。
解释:
正则表达式:
( start a capture group comprising:
\w+ one or more "word" characters
\W+ one or more "not a word" characters
\w+ one or more "word" characters
) end capture group
\W followed by non-word
/ig case insensitive, global (repeat as often as possible)
并替换为:
$1 "The thing in the first capture group (everything matched in parentheses)
\n followed by a newline
第二个问题:
顺便说一句 - 由于您询问的是“其他”问题 - 如何在...
一定数量的单词后终止句子,您可以执行以下操作:
var abbrev = mytest.replace(/((\w+\W+){5}).*$/,"$1...");
alert(abbrev);
result:
lorem ipsum dolor sit amet ...
解释:
( start capture group
( start second group (to be used for counting)
\w+ one or more "word" characters
\W+ one or more "non word" characters
){5} match exactly five of these
) end of capture group
.*$ followed by any number of characters up to the end of the string
并替换为
$1 the contents of the capture group (the first five words)
... followed by three dots
那里-一个问题有两个答案!
如果你想两者都做,那么先做“缩写一个长句子”,然后把它切成更短的片段。使用正则表达式计算多行中的单词有点困难。