Skip to content

Instantly share code, notes, and snippets.

@demouth
Created July 31, 2012 14:32
Show Gist options
  • Select an option

  • Save demouth/3217440 to your computer and use it in GitHub Desktop.

Select an option

Save demouth/3217440 to your computer and use it in GitHub Desktop.
mb_strwidth on JavaScript
;(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);
@nyangry
Copy link
Copy Markdown

nyangry commented Aug 3, 2012

これは便利ですね!

@charlesr1971
Copy link
Copy Markdown

Thanks for this. I can now convert this into Coldfusion, as I understand javascript but not PHP.

@charlesr1971
Copy link
Copy Markdown

Can I ask, how you would then convert the result into 'px'. Do I multiply the result by the font-size?

@dogeow
Copy link
Copy Markdown

dogeow commented Aug 21, 2020

nice work, man

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment