一飽眼福,你是。我只是想我會添加一個選項,並在同一時間回答你的第二個問題:
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
那裏 - 一個問題的兩個答案!
如果你想兩者都做,然後做了「縮寫一個長句子」,然後再切成短段。使用正則表達式計算多行文字有點困難。
'{2}'匹配2個空格。 – 2013-04-05 15:47:26
回車在哪裏返回正則表達式? – 2013-04-05 15:49:11
@silentboy,好吧,在測試時我正在使用昏迷,因爲我不是100%確定如何做回車......我認爲這是\ r或\ n ...但是在測試時最好不要冒險 – HowTo 2013-04-05 15:57:45