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
И если вы хотите иметь максимум вместо минимума (чтобы он никогда не превышал заданное значение):
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