Created
October 13, 2010 06:10
-
-
Save nenjiru/623554 to your computer and use it in GitHub Desktop.
表示文字数を指定してトリミング
This file contains 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
/** | |
* Trimming strings. | |
* | |
* @param {String} string 対象文字列 | |
* @param {Number} size 全角での長さ | |
* @param {String} ellipsis 省略文字(初期値 "...") | |
* @return {String} 整形文字列 | |
* | |
* @example | |
* ellipsis("表示したい全角文字数を指定", 10); | |
*/ | |
function ellipsis(string, size, ellipsis) { | |
var trim = ""; | |
var size = size * 2; | |
var ellipsis = ellipsis || "..."; | |
var length = string.length; | |
for (var i = 0; i < length; i++) { | |
var _string = string.charAt(i); | |
if (/[a-zA-Z0-9\s]/.test(_string)) size -= 1; | |
else size -= 2; | |
trim = trim + _string; | |
if (size<=0) { | |
trim += ellipsis; | |
break; | |
} | |
} | |
return trim; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment