Created
January 15, 2015 10:47
-
-
Save adammcarth/4bdce2a13b4d780dcffd to your computer and use it in GitHub Desktop.
This file contains 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 truncate(string, words) { | |
var max_chars = 6 * parseInt(words); | |
var words_array = string.split(" "); | |
var index = parseInt(words) - 1; | |
var truncated = words_array.slice(0, index).join(" "); | |
if ( truncated.length > max_chars ) { | |
truncated = string.slice(0, max_chars) + "..."; | |
} else if ( truncated === string ) { | |
truncated = string; | |
} else { | |
truncated = truncated + "..."; | |
} | |
return truncated; | |
} | |
truncate("I enjoy playing counter strike source.", 3); | |
// => I enjoy playing... | |
truncate("I enjoy playing counter strike source.", 6); | |
// => I enjoy playing counter strike sourc... | |
truncate("I enjoy playing counter strike source.", 100); | |
// => I enjoy playing counter strike source. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment