diff --git a/lib/index.js b/lib/index.js index c8d1790..ea3c368 100644 --- a/lib/index.js +++ b/lib/index.js @@ -243,7 +243,6 @@ Table.prototype.toString = function (){ - (style['padding-left'] || 0) - (style['padding-right'] || 0) , align = options.colAligns[index] || 'left'; - return repeat(' ', style['padding-left'] || 0) + (length == width ? str : (length < width diff --git a/lib/utils.js b/lib/utils.js index 1cb8072..2c39e2d 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -78,9 +78,20 @@ exports.options = options; // // see: http://en.wikipedia.org/wiki/ANSI_escape_code // -exports.strlen = function(str){ +exports.strlen = function (str) { var code = /\u001b\[(?:\d*;){0,5}\d*m/g; - var stripped = ("" + str).replace(code,''); + var stripped = ("" + str).replace(code, ""); var split = stripped.split("\n"); - return split.reduce(function (memo, s) { return (s.length > memo) ? s.length : memo }, 0); -} + // statistics of chinese characters + var chineseCharacters = + typeof str === "string" ? (str.match(/[\u4e00-\u9fa5]/gi) || []).length : 0; + return split.reduce(function (memo, s) { + if (s.length > memo) { + if (chineseCharacters) { + return s.length + chineseCharacters; + } + return s.length; + } + return memo; + }, 0); +}; diff --git a/test/index.test.js b/test/index.test.js index eaed6a2..403e22d 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -282,4 +282,25 @@ module.exports = { table.should.exist; }, + + 'test chinese width property': function (){ + var table = new Table({ + head: ['中文'], + style: { + head: [], + border: [] + } + }); + table.width.should.eql(8); + }, + 'test mixed chinese and english width property': function (){ + var table = new Table({ + head: ['中文abc123'], + style: { + head: [], + border: [] + } + }); + table.width.should.eql(14); + }, };