diff --git a/__tests__/humanize.spec.js b/__tests__/humanize.spec.js index b49aee9..a06a25a 100644 --- a/__tests__/humanize.spec.js +++ b/__tests__/humanize.spec.js @@ -193,7 +193,8 @@ describe('Truncating objects to shorter versions', () => { const objs = { str: 'abcdefghijklmnopqrstuvwxyz', num: 1234567890, - arr: [1, 2, 3, 4, 5] + arr: [1, 2, 3, 4, 5], + wrd: 'hello world' }; it('should truncate a long string with ellipsis', () => { @@ -201,6 +202,10 @@ describe('Truncating objects to shorter versions', () => { expect(Humanize.truncate(objs.str, 14, '...kidding')).toEqual('abcd...kidding'); }); + it('should truncate a string of words with ellipsis', () => { + expect(Humanize.truncateWords(objs.wrd, 1)).toEqual('hello ...'); + }); + it('should truncate a number to an upper bound', () => { expect(Humanize.truncatenumber(objs.num, 500)).toEqual('500+'); expect(Humanize.boundedNumber(objs.num, 500)).toEqual('500+'); @@ -210,6 +215,7 @@ describe('Truncating objects to shorter versions', () => { expect(Humanize.truncate(objs.str, objs.str.length + 1)).toEqual(objs.str); expect(Humanize.truncatenumber(objs.num, objs.num + 1)).toEqual(String(objs.num)); expect(Humanize.boundedNumber(objs.num, objs.num + 1)).toEqual(String(objs.num)); + expect(Humanize.truncateWords(objs.wrd, 3)).toEqual('hello world'); }); }); diff --git a/src/humanize.js b/src/humanize.js index afe4354..93d533f 100644 --- a/src/humanize.js +++ b/src/humanize.js @@ -287,21 +287,19 @@ // Truncates a string after a certain number of words. truncateWords(string, length) { const array = string.split(' '); - let result = ''; - let i = 0; - - while (i < length) { - if (exists(array[i])) { - result += `${array[i]} `; - } - i++; - } if (array.length > length) { + let result = ''; + let i = 0; + while (i < length) { + if (exists(array[i])) { + result += `${array[i]} `; + } + i++; + } return `${result}...`; } - - return null; + return string; }, truncatewords(...args) {