gpt4 book ai didi

javascript - 在 Javascript 中 chop 一个字符串,混淆最后两个测试字符串

转载 作者:行者123 更新时间:2023-11-30 08:31:45 41 4
gpt4 key购买 nike

我正在为 freecodecamp 做一个项目。

项目规则:

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.

Note that inserting the three dots to the end will add to the string length.

However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.

我的测试字符串包括:

truncateString("A-tisket a-tasket A green and yellow basket", 11) should return "A-tisket...".

truncateString("Peter Piper picked a peck of pickled peppers", 14) should return "Peter Piper...".

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) should return "A-tisket a-tasket A green and yellow basket".

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) should return "A-tisket a-tasket A green and yellow basket".

truncateString("A-", 1) should return "A...".

truncateString("Absolutely Longer", 2) should return "Ab...".

现在我已经使用 三元 运算符解决了大部分问题,所以它相当简单,除了最后两个 ('A-', 1)('Absolutely Longer', 2),我的问题是,如何才能成功完成 chop 并返回最后两个字符串的预期输出?

来源:

function truncateString(str, num) {
return str.length > num ? str.slice(0, num - 3) + '...' : str;
}

最佳答案

您需要处理 num 小于或等于 3 的情况。您可以添加另一个条件来执行此操作:

function truncateString(str, num) {
return str.length > num ? str.slice(0, num >= 3 ? num - 3 : num) + '...' : str;
}

console.log(truncateString("A-tisket a-tasket A green and yellow basket", 11));
console.log(truncateString("Peter Piper picked a peck of pickled peppers", 14));
console.log(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length));
console.log(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2));
console.log(truncateString("A-", 1));
console.log(truncateString("Absolutely Longer", 2));

关于javascript - 在 Javascript 中 chop 一个字符串,混淆最后两个测试字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36945137/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com