0
 function truncate(str, num) {
    if (str.length >= num) {
        if (num > 3) {
            str.substr(0, num - 3) + '...';
        } else {
            str.substr(0, num) + '...';
       }
    }   return str;
 }
console.log(truncate("A-tisket a-tasket A green and yellow basket", 11));

It returned me the original string A-tisket a-tasket A green and yellow basket. I wonder waht's the problem here.

3
  • You don't return.. Commented Mar 18, 2018 at 14:13
  • Never mind, I did not invoke the substr method. Should be"str=str.substr(0, num - 3) + '...';" Commented Mar 18, 2018 at 14:13
  • or just return str.substr(0, num - 3) + '...'; Commented Mar 18, 2018 at 14:13

2 Answers 2

1

substr is an immutable operation. That means that when you execute it, it doesnt change the original value of the string that you applied it to.

In order to make it work, you should save the substring in an additional variable:

function truncate(str, num) {
    if (str.length >= num) {

        if (num > 3) {
           return str.substr(0, num - 3) + '...';
        } else {
           return str.substr(0, num) + '...';
       }
    }   return str;
 }
console.log(truncate("A-tisket a-tasket A green and yellow basket", 11));
Sign up to request clarification or add additional context in comments.

Comments

0

This is because the return str is pointing the str in the function argument.Create a separate variable and assign the substring to it and return the value

function truncate(str, num) {
  let subStr = '';
  if (str.length >= num) {
    if (num > 3) {
      subStr = str.substr(0, num - 3) + '...';
    } else {
      subStr = str.substr(0, num) + '...';
    }
  }
  return subStr;
}
console.log(truncate("A-tisket a-tasket A green and yellow basket", 11));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.