javascriptd3.jsvarfile-location

How to pass a variable as a string to locate a file to be read by d3


I want my code to look at the date, assign it as a variable, and pass the variables value as the name for the appropriate file location

I'm relatively new. My posted code is my current syntax attempt.

I realize that my function does not have enough arguments. Still trying to get a grasp on all this. any help is appreciated.

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Oct", "Nov", "Dec"]; 

var date = new Date();

d3.tsv("/Data/BlueForce1/`${date.getYear()}`/`${months[date.getMonth()]}`/2019.05.12.PT.txt);

Solution

  • What you have so far...

    "/Data/BlueForce1/`${date.getYear()}`/`${months[date.getMonth()]}`/2019.05.12.PT.txt
    

    ... is a strange mix of string with template literal, and it's not even valid (you forgot the closing quote).

    You can do 2 things:

    1. Concatenating the strings:

    This is the easiest choice, just concatenate your strings:

    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Oct", "Nov", "Dec"];
    
    var date = new Date();
    
    var url = "/Data/BlueForce1/" + date.getYear() + "/" + months[date.getMonth()] + "/2019.05.12.PT.txt";
    
    console.log(url)

    1. Template literal

    For using a template literal, open and close everything with the back-ticks:

    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Oct", "Nov", "Dec"];
    
    var date = new Date();
    
    var url = `/Data/BlueForce1/${date.getYear()}/${months[date.getMonth()]}/2019.05.12.PT.txt`;
    
    console.log(url)