Xinyi Li
Xinyi Li

Reputation: 133

Try to truncate string substring in JS but did not work

 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.

Upvotes: 0

Views: 160

Answers (2)

SirPeople
SirPeople

Reputation: 4348

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));

Upvotes: 1

brk
brk

Reputation: 50291

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));

Upvotes: 0

Related Questions