【发布时间】:2016-06-20 16:10:03
【问题描述】:
我正在处理来自 freecodecamp https://www.freecodecamp.com/challenges/truncate-a-string 的编码挑战。
要完成这个,我的代码必须满足以下 3 个条件:
如果字符串(第一个参数)长于给定的最大字符串长度(第二个参数),则截断它。返回以 ... 结尾的截断字符串。
最后插入的三个点也应该增加字符串长度。
但是,如果给定的最大字符串长度小于或等于 3,则在确定截断字符串时,添加三个点不会增加字符串长度。
我能够满足前 2 个条件,但由于某种原因,当我给出字符串长度小于或等于 3 的测试用例时,我的代码会引发错误...
示例: truncateString("Absolutely Longer", 2) 应该返回 "Ab..." 而是返回 "Absolutely Longe..."
请帮忙。我的代码是https://gist.github.com/adityatejas/7857c0866f67783e71a1c9d60d3beed8。
function truncateString(str, num)
{
var truncatedStr = '';
if (str.length > num)
{
truncatedStr = str.slice(0, num-3) + "...";
return truncatedStr;
}
else if (num <= 3)
{
truncatedStr = str.slice(0, num) + "...";
return truncatedStr;
}
else return str;
}
truncateString("Adi", 1);
【问题讨论】:
-
1) 在此处发布代码 2) 提出具体问题,不要让我们做你的工作。一旦您有具体问题,我们很乐意为您提供帮助 3) 什么是“错误”
-
好吧,你的代码说如果它小于 3,添加点。
-
好的 @AndrewL 已将我的错误消息和代码编辑到我的原始问题中。感谢您的建议。
-
@epascarello 修改了我的代码,但仍然无法解决这个问题...
标签: javascript string truncation