Created
April 29, 2012 17:09
-
-
Save raspo/2551988 to your computer and use it in GitHub Desktop.
Shorten a string and optionally truncate at the last word boundary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function truncateString( string, num, useWordBoundary ){ | |
var isLong = string.length > num, | |
newString = string.replace( /(^\s)|(\s$)/gi, '' ), | |
isOneWord = newString.match(/\s/gi) === null; | |
newString = isLong ? newString.substr(0,num-1) : newString; | |
newString = ( useWordBoundary && isLong && !isOneWord ) ? newString.substr(0,newString.lastIndexOf(' ')) : newString; | |
return isLong ? newString +' ...' : newString; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment