Search code examples
javascriptarraysindexingundefinedcall

Call the (undefined) rest of an array somewhere


How could I call the rest of my array at the end of my string ? I heard about spread operator (but I am not really sure). Indeed, the number of index that I got from my array is uncertain (except for the two first).

let filePath = "folder/folder/potentialFolder/potentialFolder/.../file.txt";
let filePathBackup = filePath.split('/');
filePathBackup = `${filePathBackup[0]}/${filePathBackup[1]}/backup/${the_rest_of_my_array}`;

Thank you for your help !


Solution

  • Try using .slice() and .join() like this:

    let filePath = 'folder/folder/potentialFolder/potentialFolder/.../file.txt';
    let filePathBackup = filePath.split('/');
    let rest = filePathBackup.slice(2).join('/');
    let result = ${filePathBackup[0]}/${filePathBackup[1]}/backup/${rest}`;