FreeCodeCampChina / freecodecamp.cn

FCC China open source codebase and curriculum. Learn to code and help nonprofits.

Home Page:https://fcc.asia/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

条件一直不通过

hunyuan7890 opened this issue · comments

Challenge Truncate a string has an issue.
User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36.
Please describe how to reproduce this issue, and include links to screenshots if possible.

My code:

function truncate(str, num) {
  // 请把你的代码写在这里
  var stra = 0;
  if (str.length > num) {
    stra = str.replace(str.slice(num -3), "..." );
    //var strb = str.substr(0, num);
  } else if (num < 3) {
    stra = str.replace(str.slice(num, num), "..." );
  }
  
  else {
    stra = str.replace(str.slice(num), "" );
  }
  return stra;
}

//truncate("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length);
//truncate("A-", 1);
truncate("Absolutely Longer", 2);

truncate("A-", 1) 应该返回 "A...". 和 truncate("Absolutely Longer", 2)这两个条件一直满足不了,请帮忙看一下问题出在哪里?谢谢!

@hunyuan7890

  1. 首先,你的 slice 用的不对。先看看文档。因此你的 str.slice(num, num) 永远会得到空字符
  2. 其次,replace 用的也不好。第一个参数传入 substring 不是不行,但不推荐,因为可读性差,而且也不好控制

建议用 substr 方法。或者,你也可以选择用 slice 拼凑出结果。详情:https://singsing.io/blog/fcc/basic-truncate-a-string/

顺便,你的 stra 只赋值了一次,然后就返回了。那你其实并不需要这个变量,直接返回结果就行

var k="...";
if(num<=3){
str= str.substring(0,num)+k;
}else if(str.length>num){
str=str.substring(0,num-3)+k;
}
return str;
}