0

I'm fairly new to Javascript, and I am just trying to loop over an array, append the value of the loop iteration to a template string, and print it via console.log in a nodejs terminal.

I've written the following code to make my array:

// Get LTLAs from file
var fs = require("fs");
var text = fs.readFileSync("./LTLAs.txt", 'utf8');
var LTLAs = text.split("\n");

This gives me an array, see snippet below:

'Barking and Dagenham\r'
'Babergh\r'
'Aylesbury Vale\r'
'Ashford\r'
'Ashfield\r'
'Arun\r'
'Amber Valley\r'
'Allerdale\r'
'Adur\r'

And then I loop over this array with:

for (let i = 0; i < LTLAs.length; i++)
{
    const endpoint = `https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=ltla;areaName=${LTLAs[i]}&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}`;
    console.log(endpoint);
}

I expected this to give me a neat set of strings, where the only difference is where the areaName=${LTLAs[i]} changes for each loop iteration. Instead I get a set of incomplete strings, with only the last of the loop actually being correct, as seen below:

&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}Dagenham
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}le
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=ltla;areaName=Adur&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}

Any assistance on getting all of the strings to follow the same pattern as the final string would be appreciated.

Thanks in advance

1 Answer 1

2

You need to remove carriage return symbol ('\r') from your strings to get proper output in node js (some browsers may ignore it).

You can either iterate over array:

var LTLAs = text.split("\n").map(string => string.replace('\r', ''));

Or you can split with \r\n instead of \n:

var LTLAs = text.split("\r\n")
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thank you, can't believe I missed this. Will mark as correct ASAP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.