【JavaScript】短縮文字列作成

コード

shortMessage.js// 文字列長(全角考慮)
function mlength() {
  var len=0,
      i;
  for (i=0; i<this.length; i++) {
    len += (this.charCodeAt(i) > 255) ? 2: 1;
  }
  return len;
};
// 文字列切り出し(全角考慮)
function msubstr(start, length) {
  var s = 0;
  if (start != 0) {
    var mstart = Math.abs(start),
        direct = start/mstart,
        len = 0,
        i1 = (start < 0)? this.length-1: 0;
    for (; 0<=i1 && i1<this.length; i1+=direct) {
      len += (this.charCodeAt(i1) > 255)? 2: 1;
      if (mstart < len) {
        i1 -= direct;
        break;
      }
    }
    s = Math.max(0, i1);
  }
  var i2 = this.length;
  if (length !== void 0) {
    var len = 0;
    for (i2=s; i2<this.length; i2++) {
      len += (this.charCodeAt(i2) > 255) ? 2: 1;
      if (length < len) {
        break;
      }
    }
  }
  return this.substr(s, i2-s);
};
/**
 * 短縮文字列作成(全角文字を考慮)
 * @param {string} [type='tail'] - 種別('head':前方/'middle':中間/'tail':後方)
 * @param {string} msg - 対象文字列
 * @param {number} max - 最大桁数(全角文字を2桁として解釈する)
 * @return {string} 短縮文字列
 */
function shortMessage(type, msg, max) {
  var length = mlength;
  var substr = msubstr;

  msg = msg+'';
  var m = substr.call(msg, 0, max);
  if (m.length < msg.length) {
    if (max <= 2) {
      m = '..'.substr(0, max);
    } else if (type === 'middle') {
      var m1 = substr.call(msg, 0, Math.ceil((max/2)-1)),
          m2 = (Math.floor((max/2)-1) == 0) ? 
                '': 
                substr.call(msg,-Math.floor((max/2)-1)),
          dn = max - length.call(m1) - length.call(m2);
      m = m1 + Array(dn + 1).join('.') + m2;
    } else if (type === 'head') {
      m = substr.call(msg, -(max - 2));
      m = Array(max - length.call(m) + 1).join('.') + m;
    } else {
      m = substr.call(msg, 0, max - 2);
      m = m + Array(max - length.call(m) + 1).join('.');
    }
  }
  return m;
};

動作例

var msg = '1あ4567い0'
console.log(shortMessage('head', msg, 3));      // ..0
console.log(shortMessage('tail', msg, 3));      // 1..
console.log(shortMessage('middle', msg, 2));    // ..
console.log(shortMessage('middle', msg, 3));    // 1..
console.log(shortMessage('middle', msg, 4));    // 1..0
console.log(shortMessage('middle', msg, 5));    // 1...0
console.log(shortMessage('middle', msg, 6));    // 1....0
console.log(shortMessage('middle', msg, 7));    // 1あ...0
console.log(shortMessage('middle', msg, 8));    // 1あ..い0