Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 when to use String.raw over default template literal

I'm trying to concatenate a bunch of strings to build a query string in Javascript. Previously I have achieved this through ugly string concatenation:

var queryString = "?action=" + actionValue + "&data=" + dataValue";

But with ES6 I see that there are new methods provided that could help me achieve the same result with much nicer looking code, like string interpolation in C# 6:

string s = $"action={actionValue}&data={dataValue}"

I have tested with both default template literal and String.raw and although the syntax for each is slightly different, they both work. I'm leaning towards using String.raw in my final copy as it doesn't allow for the string to be tagged and thus tinkered with in the future like the default template literal does.

Although it does say in the MDN docs that String.raw basically calls the default template literal method but I like the syntax of String.raw better... I am calling the String.join method inside the curly braces of my string that I am formatting so maybe that is a misuse of String.raw.

Are any ES6 wizards out there able to enlighten me and provide reasons for one over the other?

My code:

var defaultTemplateStringUrl = `@Url.Action("DownloadMultiple")?inIds=${inData.join(',')}&outIds=${outData.join(',')}&truckId=${truckId}`;
var rawStringUrl = String.raw `@Url.Action("DownloadMultiple")?inIds=${inData.join(',')}&outIds=${outData.join(',')}&truckId=${truckId}`;

window.open( /*url goes here*/);
like image 342
Matt Stannett Avatar asked Feb 08 '23 17:02

Matt Stannett


1 Answers

A template literal produces a string. If you use String.raw, you will get the raw form of that string:

`a\tb`;           // "a b"
String.raw`a\tb`; // "a\tb"

So you should use String.raw only when you want the raw form.

like image 147
Oriol Avatar answered Feb 11 '23 15:02

Oriol