gpt4 book ai didi

javascript - 为什么 str.endsWith ("-") 不返回 true?

转载 作者:行者123 更新时间:2023-12-03 02:11:35 25 4
gpt4 key购买 nike

我 chop 字符串的函数必须满足某些条件,但我在其中一些条件上遇到了麻烦。

尝试满足这些条件

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

应该返回“A-tisket...”

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

应该返回“Peter Piper...”

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

应该返回“A-tisket a-tasket A green and Yellowbasket”

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

应该返回“A-tisket a-tasket A green and Yellowbasket”

这是我无法满足的

truncateString("A-", 1) 

应该返回“A...”

truncateString("Absolutely Longer", 2) 

应该返回“Ab...”

我的代码的测试片段:

function truncateString(str, num) {
// Clear out that junk in your trunk

var truncated = str.substr(0, num);
var trunky = str;

if (truncated.endsWith("-") == true) {
return truncated.substr(0, (num) - 3) + "...";
} else if (truncated.endsWith("i") == true) {
return truncated.substr(0, (num) - 3) + "...";
} else if (truncated.endsWith("b") == true) {
return truncated.substr(0, (num)) + "...";
} else if (truncated.endsWith('/-') == true) {
return truncated.substr(0, (num)) + "...";
} else
return str;
}

var test = "A-tisket a-tasket A green and yellow basket";
console.log(truncateString(test, test.length));

最佳答案

根据Mozilla developer documentation ,函数 String.prototype.substr 可以接受起始值和长度。

就您而言,您通过应用 "A-".substr(0, 1)"A-" chop 为 "A" code> 因此它不会通过标题中的测试:truncated.endsWith("-")

关于javascript - 为什么 str.endsWith ("-") 不返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49541008/

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