Search code examples
javascripttextalert

Create a function to truncate text and adding "..." at the end of the text truncated. JS


I'm new and learning JS. As described in the title I want that the browser 'alert' the text truncated +'...', if his lenght is higher than the maxlenght. The browser doesn't do so, someone can help me please?

let str = prompt('Insert Text', '');
let maxLenght = +prompt('write max length', '');

function truncate(str, maxLenght) {
  if (str.length > maxLenght) {
    return str.slice(0, (maxLenght - 1)) + '...';
  } else {
    return str
  }
}

alert(truncate());


Solution

  • You need to pass the variables to the function. Also you don't need to use maxLenght - 1 because slice doesn't include the last index by default.

    let str = prompt('Insert Text', '');
    let maxLenght = +prompt('write max length', '');
    
    function truncate(str, maxLenght) {
      if (str.length > maxLenght) {
        return str.slice(0, (maxLenght)) + '...';
      } else {
        return str
      }
    }
    
    alert(truncate(str, maxLenght));