DEV Community

Cover image for Truncate any string(first argument) at a given num integer (second argument)
Cesare
Cesare

Posted on

Truncate any string(first argument) at a given num integer (second argument)

The problem:

we have a string (first argument) and we want to truncate it if the length is above the num integer (second argument).

input:

  • truncateString("A-tisket a-tasket A green and yellow basket", 8)

output:

the first 8 elements of the string plus append "..." at the end of the string

  • A-tisket...

Solution 1:

Step 1

under the function declare a conditional if statement:

if (str.length > num)

Step 2

always under the function's curly brackets insert the return statement that stops the function and gives the value of the function:

return str.slice(0,num) + "..."

the above line of code uses the slice() method that takes two integer as argument for the start and stops index positioning. and append the string "..." using the + operator.

The whole function below

function truncateString(str, num) {
if (str.length > num){
   return str.slice(0,num) + "...";

}
   else {
     return str;
   } 

}

(truncateString("A-tisket a-tasket A green and yellow basket", 8);
Enter fullscreen mode Exit fullscreen mode

Solution2(Using conditional ternary operator):

Basically the same but without the if statement.

With this solution, we reduce of 50% the lines of codes to only one line!

remember ternary operator is one line which must include:

condition? expression if true: expression if false;

The syntax must always include the ? and :

so -> str.length > num ? return str.slice(0,num) + "..." : str;

The code block using ternary operator:

function truncateString(str, num) {
return str.length > num ? str.slice(0,num) + "...": str 
}


console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)