zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Truncate a string #297

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

挑战

如果字符串超过给出的指定长度,则以...代替,...算入字符串长度。

如果字符串长度小于等于三,则直接加...

代码


function truncateString(str, num) {
  // Clear out that junk in your trunk
  if(num>=str.length){
    return str;
  }else if(num>3 && num<str.length){
    var strSlice=str.slice(0,num-3);

    return strSlice+"...";

  }else if(num<=3){

    var strShort=str.slice(0,num)+"...";
    return strShort;

  }  

}

truncateString("Absolutely Longer", 2);

结果显示

image

帮助

String.prototype.slice() [ ]( ) [ ]( )

来源

https://www.freecodecamp.org/challenges/truncate-a-string

zilongxuan001 commented 6 years ago

经验谈20180328

看似需要两个if即可,其实是三个,这坑够深的。

另外是数字的范围,需要不断调整,.slice(0,3)是从索引0开始,到索引3,但不包括索引3,所以范围是 0<=str<3.