0

我在这里写了这段代码:

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从我的变量中删除。

4

3 回答 3

2

这应该工作

title.replace(/\s([^" "]+)$/, '...');

检查这里http://jsfiddle.net/UwtJQ/2/

于 2013-10-09T19:27:11.367 回答
2

如果前 20 个字符中没有空格,我不知道您打算做什么,但这里有一个可能的解决方案:

var result;
if(title.indexOf(" ") > 20){
    // no space in the first 20 characters
    }else{
        result = title.substring(0, title.substring(0,20).lastIndexOf(" ")) + "...";
}
于 2013-10-09T19:24:54.413 回答
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 '...'
于 2013-10-09T19:27:15.793 回答