簡體   English   中英

從句子中刪除除三個單詞以外的所有單詞,並使用jquery在該三個句子之后添加三個點

[英]Remove all but the three word from a sentence and add three dots after that three sentence using jquery

我想從句子中刪除除三個單詞以外的所有單詞,並使用jquery在該三個句子之后添加三個點。 例如,如果句子為“我們定期評估我們的借款人。請參閱我們的評估”,以便定期刪除“ 借款人。請參閱我們的評估請參閱我們的評估 ”,我想這樣表示:“ 我們評估我們的。 “我想這里是代碼

您可以使用CSS規則text-overflow來實現此目的。 這是您可以用來實現所需結果的類:

.prevent-overflow { 
    white-space: nowrap; 
    overflow: hidden; 
    text-overflow: ellipsis
}​

下面是它的功能細分: white-space: nowrap; 當到達元素的邊緣時,停止將文本表單換行。 overflow:hidden告訴文本永遠不會出現在元素和text-overflow: ellipsis的范圍之外text-overflow: ellipsis告訴瀏覽器在任何內容被截斷時將...放置在文本的末尾(請參閱text-overflow @ MDN )。

將其應用於尺寸會截斷其中包含的文本的元素。

我創建了一個jsfiddle來演示其用法。

注意: jsfiddle在元素( <div style="clear:both"></div> )的末尾包含一個div,這會阻止省略號的工作(請參閱此jsfiddle ),我建議您應用clear:both; 而不是整個div,或者找到另一種方法來實現<div>的目的。

Javascript僅支持先行但不支持落后...但是的,存在解決方法

這將為您服務...

var str="How are you doing today?";

regexp = new RegExp('(' + str.match(/(\w+\s){2}\w+/g)+ ')?.*'); //fetches first 3 words and makes regural expression to lookbehind this positively
var output = str.replace(regexp, function($0, $1){     //mimicks positive lookbehind
    return $1 ? $1 + '...' : $0;
});

document.writeln(output );

更新-這僅適用於“你好嗎..” ...所以請使用以下內容

這是一個很好的教程,用於模擬javascript中的負向和正向隱藏,因為它不支持它。

Javascript僅支持先行

http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

更新-這對於您的示例中的任何東西都適用

var str="We evaluate our borrowers on a periodic basis. See our evaluationsWe evaluate our borrowers on a periodic basis. See our evaluationsWe evaluate our borrowers on a periodic basis. See our evaluations";

var first_three = str.match(/(\w+\s){2}\w+/);

regexp = new RegExp('(' + first_three[0] + ')?.*'); //fetches first 3 words and makes regural expression to lookbehind this positively
var output = str.replace(regexp, function($0, $1){     //mimicks positive lookbehind
    return $1 ? $1 + '...' : $0;
});

document.writeln(output);​

和正在運行的jsFiddle http://jsfiddle.net/Rpq7b/2/

嘗試以下功能:

function myfunction(val)
{
    temp = val.split(' ');

    if(val.length >= 2)
    {
         val = temp[0] + ' ' + temp[1] + ' ' + temp[2] + ' ..';
    }

    return val;
}

我想這應該工作

 var yourText = " We evaluate our borrowers on a periodic basis", 

 result = yourText.replace(/^(.{15}[^\s]*).*/, "$1");

 alert(result);

注意:將代碼中的15乘以任意數量

要獲得省略號,您可以添加result + "&hellip;"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM