I 开发者_StackOverflowhave a long text. ex:
var text = "get snippet text using javascript?";
How can I write a method to get the snippet, not substring:
Ex: snippet(text,10) -> "get snippet..." not "get snippe" (10 characters). it means if the last character not a space or dot, we must get more characters until reach space or dot.
Any help?
Not tested thoroughly:
function getSnippet(text, length) {
var rx = new RegExp("^.{" + length + "}[^ ]*");
return rx.exec(text)[0];
}
console.log(getSnippet("get snippet text using javascript?", 1)); // get
console.log(getSnippet("get snippet text using javascript?", 3)); // get
console.log(getSnippet("get snippet text using javascript?", 10)); // get snippet
console.log(getSnippet("get snippet text using javascript?", 11)); // get snippet
You can add the ellipsis when the returned string is shorter than original string.
function intelligentlyTruncate( text, threshhold )
{
for(var i = threshhold; i < text.length; i++ )
{
if( /^\s/.test(text.substr( i, 1 ) ) )
return text.substr( 0, i ); // + '...' if you want the elipsis.
}
return text;
}
console.log( intelligentlyTruncate("get snippet text using javascript?", 5) );
// get snippet
And if you want to have a maximum instead of a minimum (so it will never be longer than a given value):
function intelligentlyTruncate( text, threshhold )
{
for(var i = threshhold - 1; i >= 0; i-- )
{
if( /^\s/.test(text.substr( i, 1 ) ) )
return text.substr( 0, i ); // + '...' if you want the elipsis.
}
return text;
}
console.log( intelligentlyTruncate("get snippet text using javascript?", 5) );
// get
You can use indexOf and specify the start point to find the next space.
var text = "get snipped text using javascript?";
function getComplete(str, len) {
if (str.length > len) {
var i = str.indexOf(" ", len);
return str.substring(0, i);
}
return str;
}
getComplete(text, 10) // "get snipped";
A prototype riff on theprogrammer's answer:
String.prototype.getComplete = function(len) {
var str = this;
if (str.length > len) {
var i = str.indexOf(" ", len);
return str.substring(0, i);
}
return str;
}
//Usage
mystr = mystr.getComplete(500);
Not sure I understand your question completely, but I guess regular expression can be used in this case:
text.match(/^(\S+ [^ .]+)/)[1]
returns
"get snippets"
function snippet(str,len) {
newStr=str.substring(0, len);var i = len;
while(str[i]!=' ' && str[i]!='.')
newStr+=str[i++];
return newStr+"...";
}
精彩评论