为什么没有str.endsWith(" - ")返回true?

时间:2018-03-28 17:45:05

标签: javascript

我截断字符串的功能必须符合某些条件,但我遇到其中一些问题。

努力满足这些条件

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 yellow basket"

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 yellow basket"

这是我遇到的问题

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));




1 个答案:

答案 0 :(得分:1)

根据Mozilla developer documentation,函数String.prototype.substr可以包含开头和长度。

在您的情况下,您通过应用"A-""A"截断为"A-".substr(0, 1),因此它不会在您的标题中通过测试:truncated.endsWith("-")