Return a string, after truncating to a specified length. - Node.js String

Node.js examples for String:String Value

Description

Return a string, after truncating to a specified length.

Demo Code


/**/*  w  w w  .ja  va 2  s.co  m*/
* Return a string, after truncating to a specified length.
* @param {string} the string to truncate
* @param {integer} the length to truncate
* @param {string} a string to append, if the string was truncated
* @returns {string} the truncated string 
*/
Solstice.String.truncate = function(str, len, marker) {
    if (str == null) {
        return '';
    }

    if (!len) len = 30;
    if (!marker) marker = '...';

    if (marker.length > len) return str;
    if (0 > len) return str;

    if (str.length > len) {
        str = str.substring(0, (len - marker.length));
        str += marker;
    }
    return str;
}

Related Tutorials