Follow

Follow

# Truncate a String - JavaScript Solution & Walkthrough

## (08/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.

Benjamin Semah
·Apr 8, 2022·

• 08/16 Truncate a String
• Understanding the Challenge
• Pseudocode
• Solving the Challenge
• Final Solution
• Congratulations!

## 08/16 Truncate a String

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a `...` ending.

``````function truncateString(str, num) {

return str;
}

``````

Credit: FreeCodeCamp.org

## Understanding the Challenge

In this challenge, you'll be given a string (str) and a number (num). Your task is to complete the function such that it checks whether the string is longer than the given number. If it is, then the function should truncate `str` at the point where the length is equal to `num`. And then add the three dots `...` to it.

For example given a string `"abcde"` and a number `3`, the function should return `abc...`

If the length of `str` is equal to or less than `num`, then we should return the string just as it is.

## Pseudocode

``````Given a string and a number
compare length of string and number
if length of string is less than or equal to number
return string just as it is
if length of string is greater than number
truncate string to have equal length of number
return truncated string with "..." added at the end
``````

## Solving the Challenge

First we need to compare the length of the given string and the number. If the length of the string is less than or equal to num `str.length <= num`, the function should return string just as it has been given.

``````if (str.length <= num) {
return str
}
``````

However, if the length of the string is greater than the given number, then the function should truncate the string to be equal to the given maximun string length `str.length > num`. The function should also add `...` to the end.

To truncate the string, we can use the `.substring()` method. This method helps us to extract part of a string. It takes two arguments. The first argument is where the extraction should begin. The second argument is where it should end. In the case of the `truncateString` function, the extraction will begin at first character of the string (0) and end at the character at the index of `num`.

``````str.substring(0, num) + "..."
``````

## Final Solution

``````function truncateString(str, num) {
if (str.length <= num) {
return str
} else {
return str.substring(0, num) + "..."
}
}