js string ellipsis code example

Example 1: javascript cut string if too long

if (string.length > 25) {
  string = string.substring(0, 24) + "...";
}

//or 

function truncate(str, n){
  return (str.length > n) ? str.substr(0, n-1) + '…' : str;
};

//or with CSS

p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

//or with replace

short = long.replace(/(.{7})..+/, "$1…");

Example 2: javascript ellipsis

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

/* Spread syntax (...) allows an iterable such as an array expression or string 
to be expanded in places where zero or more arguments (for function calls) 
or elements (for array literals) are expected, or an object expression to be 
expanded in places where zero or more key-value pairs (for object literals) 
are expected. */

// ... can also be used in place of `arguments`
// For example, this function will add up all the arguments you give to it
function sum(...numbers) {
  let sum = 0;
  for (const number of numbers)
    sum += number;
  return sum;
}

console.log(sum(1, 2, 3, 4, 5));
// Expected output: 15

// They can also be used together, but the ... must be at the end
console.log(sum(4, 5, ...numbers));
// Expected output: 15

Example 3: ellipses in js

//Example: 
const numbers1 = [1, 2, 3, 4, 5];
const numbers2 = [ ...numbers1, 1, 2, 6,7,8]; 
// this will be [1, 2, 3, 4, 5, 1, 2, 6, 7, 8]