2013-10-09 57 views
0

代替我寫了這個代碼在這裏:JQuery..find最接近的空間和

var title = "This is my comment for my title"; 
title.replace(/['"`!#()_:\/\.\?]|&[^;]+;/g, '').substring(0, 20); 

這讓我的前20個字符,但我想找到最接近的空間和...

如何更換我會那樣做嗎?

新手在JQuery的

現在它返回...... This is my comment f,我想回This is my comment...

我嘗試添加以下代碼:

title = title.substr(title.indexOf(" ")) + "..."; 

,但它刪除This我變量。

+0

最接近什麼? – aarryy

+2

你應該添加標題應該看起來像什麼之後。 – rojoca

+0

更新了我的問題 – user1269625

回答

1

我不知道你打算做的,如果沒有在第一個20個字符的空間,但這裏有一個可能的解決方案是什麼:

var result; 
if(title.indexOf(" ") > 20){ 
    // no space in the first 20 characters 
    }else{ 
     result = title.substring(0, title.substring(0,20).lastIndexOf(" ")) + "..."; 
} 
0

使用此:(我還沒有在此代碼中使用jQuery的)

var arr = title.replace(/['"`!#()_:\/\.\?]|&[^;]+;/g, '').substring(0, 20).split(" "); 
arr.splice(arr.length - 1, 1); 
var message = arr.join(" ") + "..."; //the message variable is the string with '...'