Skip to content

Instantly share code, notes, and snippets.

@ValorLin
Last active August 29, 2015 14:20
Show Gist options
  • Save ValorLin/86bf8f058ea374c8b7c5 to your computer and use it in GitHub Desktop.
Save ValorLin/86bf8f058ea374c8b7c5 to your computer and use it in GitHub Desktop.
Omit middle for long string, middle version of `text-overflow: ellipsis`
/**
* Omit middle when a string is too long.
* Example:
* ```
* omitMiddle('veryveryveryveryveryveryveryveryveryverylongfilename.txt')
* // result: 'very......name.txt'
* ```
* @param str
* @param [replacement] Default: ......
* @param [frontCount] How many words you want to keep in the front. Default: 4
* @param [endCount] How many words you want to keep in the end. Default: 8
* @returns {string}
*/
function omitMiddle(str, replacement, frontCount, endCount) {
frontCount = frontCount || 4;
endCount = endCount || 8;
replacement = replacement || '......';
var re = new RegExp('^(.{' + frontCount + '}).{' + (replacement.length + 1) + ',}(.{' + endCount + '})$');
return str.replace(re, '$1' + replacement + '$2');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment