Created
July 31, 2012 14:32
-
-
Save demouth/3217440 to your computer and use it in GitHub Desktop.
mb_strwidth on JavaScript
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
;(function(ns){ | |
/** | |
* mb_strwidth | |
* @param String | |
* @return int | |
* @see http://php.net/manual/ja/function.mb-strwidth.php | |
*/ | |
var mb_strwidth = function(str){ | |
var i=0,l=str.length,c='',length=0; | |
for(;i<l;i++){ | |
c=str.charCodeAt(i); | |
if(0x0000<=c&&c<=0x0019){ | |
length += 0; | |
}else if(0x0020<=c&&c<=0x1FFF){ | |
length += 1; | |
}else if(0x2000<=c&&c<=0xFF60){ | |
length += 2; | |
}else if(0xFF61<=c&&c<=0xFF9F){ | |
length += 1; | |
}else if(0xFFA0<=c){ | |
length += 2; | |
} | |
} | |
return length; | |
}; | |
/** | |
* mb_strimwidth | |
* @param String | |
* @param int | |
* @param int | |
* @param String | |
* @return String | |
* @see http://www.php.net/manual/ja/function.mb-strimwidth.php | |
*/ | |
var mb_strimwidth = function(str,start,width,trimmarker){ | |
if(typeof trimmarker === 'undefined') trimmarker=''; | |
var trimmakerWidth = mb_strwidth(trimmarker),i=start,l=str.length,trimmedLength=0,trimmedStr=''; | |
for(;i<l;i++){ | |
var charCode=str.charCodeAt(i),c=str.charAt(i),charWidth=mb_strwidth(c),next=str.charAt(i+1),nextWidth=mb_strwidth(next); | |
trimmedLength += charWidth; | |
trimmedStr += c; | |
if(trimmedLength+trimmakerWidth+nextWidth>width){ | |
trimmedStr += trimmarker; | |
break; | |
} | |
} | |
return trimmedStr; | |
}; | |
ns.mb_strwidth = mb_strwidth; | |
ns.mb_strimwidth = mb_strimwidth; | |
})(window); |
Thanks for this. I can now convert this into Coldfusion, as I understand javascript but not PHP.
Can I ask, how you would then convert the result into 'px'. Do I multiply the result by the font-size?
nice work, man
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
これは便利ですね!