Created
January 13, 2020 16:00
-
-
Save crates/f54d94c088b5c34fc6d7ed7bdac5467c to your computer and use it in GitHub Desktop.
String truncation and trim methods
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
if (typeof String.prototype.trimAll !== 'function') { | |
String.prototype.trimAll = function() { /* Trim all whitespace from strings: */ | |
var sString = this; | |
if (typeof(sString) === 'undefined' || (!sString)) return ''; | |
while(sString.substring(0,1) == ' ' || | |
sString.substring(0,1) == '\r' || | |
sString.substring(0,1) == '\n') { | |
sString = sString.substring(1, sString.length); | |
} | |
while (sString.substring(sString.length-1, sString.length) == ' ' || | |
sString.substring(sString.length-1, sString.length) == '\r' || | |
sString.substring(sString.length-1, sString.length) == '\n') { | |
sString = sString.substring(0,sString.length-1); | |
} | |
return sString; | |
}; | |
} | |
if (typeof String.prototype.truncate !== 'function') { | |
String.prototype.truncate = function(n, useWordBoundary = true) { /* Truncate strings: */ | |
var tooLong = this.length > n; | |
var s_ = tooLong ? this.substr(0, n - 1).trimAll() : this; | |
s_ = useWordBoundary && tooLong ? s_.substr(0, s_.lastIndexOf(' ')) : s_; | |
if (tooLong) { | |
while (/[^A-Z]$/i.test(s_)) { | |
s_ = s_.substr(0, s_.length - 1); | |
} | |
} | |
return tooLong ? s_ + '...' : s_; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment