-
Notifications
You must be signed in to change notification settings - Fork 660
Simple one liner JS for string truncate
pjackson28 edited this page Mar 19, 2013
·
1 revision
On any string, you can use either of these following .replace() calls. The first one truncates on any string 160 characters or longer and chops it at 159 characters plus an ellipsis. The second one looks for a string 160 characters or longer and chops it at the closest space character past 159 characters – adding an ellipsis at the end.
.replace(/^(.{159}).+$/, '…')
.replace(/^(.{159,}?(?=\s)).+$/, '…')
You can customize the length at which it truncates and what it will replace the truncated text with quite easily.