Last active
August 29, 2015 14:20
-
-
Save ValorLin/86bf8f058ea374c8b7c5 to your computer and use it in GitHub Desktop.
Omit middle for long string, middle version of `text-overflow: ellipsis`
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
/** | |
* 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