你有很多选择。我只是想再加上一个选项,同时回答你的第二个问题:
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
一个问题有两个答案!
如果你想同时做这两件事,那么先缩短一个长句,然后将其分成更短的片段。使用正则表达式跨多行计算单词数量有点困难。