Escaping single quotes in a console log output

I am putting custom JavaScript into a GTM container to loop through an array of hyperlinks that I have used .map to create. Then create a JSON output based on the values within it (using a combination of the index number and the href values).

NOTE: ES6 solutions will not work here as GTM unfortunately does not support it.

I am having trouble with escaping the single quotation marks:

I want the output to be like this:

'id': '1',
'name': 'https://example.com',
'creative': 'store-banner',
'position': 'slot-1'

and below is my attempt to print out the array into console log and assign it the appropriate syntax:

for (var i = 0; i < carouselArray.length; ++i) {
  console.log("'id':" + '\(i+1)'\ + ", 'name': " + '\carouselArray[i]'\ + ", 'creative': store-banner, 'position': slot-" + \'(i+1)'\);
}

I am trying to get the dynamic values be surrounded by single quotations but I keep getting syntax errors and can not seem to figure out what I am doing wrong. Can someone please help to show me what I am missing or doing incorrect?

111 thoughts on “Escaping single quotes in a console log output”