Skip to content

Instantly share code, notes, and snippets.

@Cside
Created February 1, 2011 16:22
Show Gist options
  • Save Cside/806088 to your computer and use it in GitHub Desktop.
Save Cside/806088 to your computer and use it in GitHub Desktop.
全角・半角混じった文字をいい感じにsubstrする
function truncate(str, size, suffix) {
if (!str) str = '';
if (!size) size = 32;
if (!suffix) suffix = '...';
var b = 0;
for (var i = 0; i < str.length; i++) {
b += str.charCodeAt(i) <= 255 ? 1 : 2;
if (b > size) {
return str.substr(0, i) + suffix;
}
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment