FreeCodeCamp:Truncate a string

要求:

 

用瑞兹来截断对面的退路!

 

截断一个字符串!

 

如果字符串的长度比指定的参数num长,则把多余的部分用...来表示。

 

切记,插入到字符串尾部的三个点号也会计入字符串的长度。

 

但是,如果指定的参数num小于或等于3,则添加的三个点号不会计入字符串的长度。

 

结果:

 

  • truncate("A-tisket a-tasket A green and yellow basket", 11) 应该返回 "A-tisket...".
  • truncate("Peter Piper picked a peck of pickled peppers", 14) 应该返回 "Peter Piper...".
  • truncate("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".
  • truncate("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".
  • truncate("A-", 1) 应该返回 "A...".
  • truncate("Absolutely Longer", 2) 应该返回 "Ab...".

 

代码:

 

 1 function truncate(str, num) {
 2   // Clear out that junk in your trunk
 3   var newstr;
 4   var strlength=str.length;
 5   var newstrlength;
 6   if(num>3&&strlength<=num){
 7     newstr=str;
 8   }else if(num>3&&strlength>num){
 9     newstrlength=num-3;
10     newstr=str.slice(0,newstrlength).concat("...");
11   }else{
12     newstrlength=num;
13     newstr=str.slice(0,newstrlength).concat("...");
14   }
15   return newstr;
16   //return str;
17 }
18 
19 truncate("A-tisket a-tasket A green and yellow basket", 11);

 

posted @ 2016-11-09 21:34  tmj  阅读(281)  评论(0编辑  收藏  举报