Algorithm Exercise 9: String Interception Algorithm

The algorithm is demonstrated with a small example:

If the length of the string is longer than the given parameter num, the extra part is ...used to represent.

Remember, the three dots inserted at the end of the string also count towards the length of the string.

However, if the specified parameter numis less than or equal to 3, the added three dots do not count towards the length of the string.

Functions are used here, slice() methods that extract part of a string and return a new string.

  Function description: beginSliceExtract the characters in the original string starting from this index (base 0). If the value is negative, it will be treated as  if it is an optional value sourceLength + beginSlice here sourceLength 是字符串的长度 (for example, if it beginSlice is -3 it is treated as:  sourceLength - 3) . endSliceEnd the extraction string at this index (base 0). If this parameter is omitted, sliceit will extract all the way to the end of the string. If the parameter is negative, it is treated as sourceLength + endSlice, where sourceLength is the length of the string (eg, if endSlice is -3, then, sourceLength - 3). Returns a new string extracted from the original string.

function truncate(str, num) {
    if(num<=3){
        str=str.slice(0,num)+"...";
    }else if(num<str.length){
        str=str.slice(0,num-3)+"..."
    }
return str;
}

truncate("A-tisket a-tasket A green and yellow basket", 11);//A-tisket...

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325209981&siteId=291194637