Template Strings Without Variable Interpolation - javascript

Is it possible to have a template string in JavaScript that does not interpolate the variable values? I would like to have actual JS code blocks (which will be multi-line and contain escape sequences) like this example:
...
return String.raw`console.log(\`Here is my code:\n\n ${code}\`);`
that I can pass between functions in my Node.js app. I have no problem escaping backticks but I'd like to know if there's an easy way to stop interpolation of the variables so that I can have template strings nested inside of my template string.
I know that one option is to define code as let code = '${code}'; but I was wondering if there was a cleaner way to do it where interpolation was completely turned off in the same way that String.raw turns off interpretation of escape sequences.

Related

Passing a multiline string as parameter to js function

When calling displayBarNotification(stringIPass, 'success', 3500) of nopcommerce originally defined in public.common.js seems the call fails when stringIPass contains newlines.
The error on the client-side was something like
Unexpected line break in a string literal
I tried replacing the C# newline character in the ajax function to the js equivalent and it worked. However, I intend to keep the "newlines" for readability reasons. What approach would you suggest?
Pardon me for the lack of the exact error expr. but it's because I'm currently not at work. I will update tomorrow if necessary.
Official documentation:
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Use back-ticks ( ` ) to introduce a template literal:
var example = `
this
is
a
test
`;
console.log(example);

String.raw output "${" and bacticks

I am using String.raw to hold the contents to hold a regex that contains values like ${somevalue} in a RegExp I have. It works except there appears to be no way to escape ${} or backticks.
For example this doesn't work.
String.raw`${}` // error
String.raw`$\{}` // wrong output
String.raw`\${}` // wrong output
String.raw`\`` /wrong output
Unfortunately the best solution I can come up with is the following.
String.rawer= (s)=>{return s.raw[0].replace(/\\\{/g,"{").replace(/\\`/g,'`').replace(/\\\\$/,'\\')}
Is there a solution that is less ugly that doesn't require defining my own function and subsequent function calls?
I think this looks cleaner than what you have
console.log(String.raw`${"${}"}`)
You would have to put the ${} inside a ${} and put quotes around it inside. But this is an annoying issue that doesn't really have a simple solution to it, that I am aware of anyways.

How to Use ES6 Template Literals in Freemarker? [duplicate]

I'm trying to use Freemarker in conjunction with jQuery Templates.
Both frameworks use dollar sign/curly brackets to identify expressions for substitution (or as they're called in freemarker, "interpolations") , e.g. ${person.name} .
So when I define a jQuery Template with expressions in that syntax, Freemarker tries to interpret them (and fails).
I've tried various combinations of escaping the ${ sequence to pass it through Freemarker to no avail - \${, \$\{, $\{, etc.
Inserting a freemarker comment in between the dollar and the curly (e.g. $<#-- -->{expression}) DOES work - but I'm looking for a more concise and elegant solution.
Is there a simpler way to get a Freemarker template to output the character sequence ${?
This should print ${person.name}:
${r"${person.name}"}
From the freemarker docs
A special kind of string literals is the raw string literals. In raw string literals, backslash and ${ have no special meaning, they are considered as plain characters. To indicate that a string literal is a raw string literal, you have to put an r directly before the opening quotation mark or apostrophe-quote
For longer sections without FreeMarker markup, use <#noparse>...</#noparse>.
Starting with FreeMarker 2.3.28, configure FreeMarker to use square bracket syntax ([=exp]) instead of brace syntax (${exp}) by setting the interpolation_syntax configuration option to square_bracket.
Note that unlike the tag syntax, the interpolation syntax cannot be specified inside the template. Changing the interpolation syntax requires calling the Java API:
Configuration cfg;
// ...
cfg.setInterpolationSyntax(SQUARE_BRACKET_INTERPOLATION_SYNTAX);
Then FreeMarker will consider ${exp} to be static text.
Do not confuse interpolation syntax with tag syntax, which also can have square_bracket value, but is independent of the interpolation syntax.
When using FreeMarker-based file PreProcessor (FMPP), either configure the setting via config.fmpp or on the command-line, such as:
fmpp --verbose --interpolation-syntax squareBracket ...
This will call the appropriate Java API prior to processing the file.
See also:
https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html
http://fmpp.sourceforge.net/settings.html#templateSyntax
Another option is to use #include with parse=false option. That is, put your jQuery Templates into the separate include page and use parse=false so that freemarker doesn't try and parse it.
This would be a good option when the templates are larger and contain double quotes.
I had to spent some time to figure out the following scenarios to escape ${expression} -
In Freemarker assignment:
<#assign var = r"${expression}">
In html attribute:
Some link
In Freemarker concatenation:
<#assign x = "something&"+r"${expression}"/>
If ${ is your only problem, then you could use the alternate syntax in the jQuery Templates plugin like this: {{= person.name}}
Maybe a little cleaner than escaping it.
Did you try $$?
I found from the Freemarker manual that ${r"${person.name}"} will print out ${person.name} without attempting to render it.
Perhaps you should also take a look at Freemarker escaping freemarker
I can confirm that the
${r"${item.id}"}
is the correct way as an example.
So I kinda full example will look like
<span> Remove </span>
and the output will be :
<span> Remove </span>
In the case when you want to use non-raw strings so that you can escape double quotes, apostrophes, etc, you can do the following:
Imagine that you want to use the string ${Hello}-"My friend's friend" inside of a string. You cannot do that with raw strings. What I have used that works is:
${"\x0024{Hello}-\"My friend's friend\""}
I have not escaped the apostrophe since I used double quotes.

Do the single quote (') and double quote (") work in jQuery like they do in PHP?

Does either the single quote (') or double quote (") have a function where they will parse through the string and replace variables with values? I remember that in PHP the parsing engine will parse through the string and automatically switch out any variables with their values (I don't remember which actually has that effect off the top of my head) so you don't have to type "somestring" + aVariableusing the concatenation
operator. in what I have read through so far on http://www.tutorialspoint.com/jquery/jquery-basics.htm I haven't been able to find anything about it. Also unless I missed it the post When to use double or single quotes in JavaScript? does not directly cover this information.
Single quotes and double quotes are identical in JavaScript and do not interpolate variables. In my experience it's good practise to stick with single quotes in JS, allowing you to use double quotes inside those strings (without escaping) for things like HTML attributes.
However, ES2015 introduced "template strings" using backticks, which are somewhat like PHP's strings in that they can interpolate into a string, and are if anything more powerful because they'll actually interpolate any expression, not just plain variables:
let bar = 'bar';
let foo = `${bar}`;
let FOO = `${bar.toUpperCase()}`;
No, there is no such thing as variable interpolation in JavaScript (and therefore jQuery)
And that's a very good thing! While PHP has all variables identified by $ at the start, JavaScript does not. So even a simple string such as "Hello world!" could go horribly wrong if you had a variable called world...
You may be interested in a templating system, of which there are many options out there - a quick Google search will turn up results, but here's a list of some with examples and stuff.

Can I avoid code duplication by referencing one Javascript Regexp literal inside another?

Is there a simple way to refer to one Javascript literal (e.g. "string") within another regexp literal?
Kind of familiar with Javascript Regexp but far from a guru. Trying to write a simple parser for a small handful of expression types. E.g. One type is expressions like:
`value gender 1='Male' 2 ='Female' 3="Didn't answer" >3 = 'Other';
Rather than write a whole parser in say, Jison, and the attendant learning curve, I thought it would be simple enough to use RegExp.
It appears Javascript Regexp can't capture an arbitrary number of repeating subgroups, and there's no clear character to split on, I'm parsing subgroups with their own regexps.
The following works okay, but the regexp literals are far from DRY, and all but unreadable. Each higher level construct repeats the lower level constructs.
var re_value_stmt = /value\s+(\w+)((?:\s+(?:[^=]+[=](?:(?:["][^"]+["])|(?:['][^']+[']))))+)/i
var re_value_clause = /([^=]+[=](\s*(?:(['][^']*['])|(["][^"]*["])))+)/ig
var re_value_elems = /([^=]+)[=]\s*(?:(?:[']([^']*)['])|(?:["]([^"]*)["]))/ig
console.log(re_value_elems.exec("1='Male'"));
console.log(re_value_clause.exec("1=\"Male\" 2=\"Female\""));
console.log(re_value_stmt.exec("value gender 1='Male' 2='Female'"));
For instance, (?:(?:["][^"]+["])|(?:['][^']+['])) just means QuotedString. Can I write that instead?
Is there a simple way to refer to one Javascript literal (e.g. "string") within another regexp literal? Specifying regexp by munging strings might work, but also seems awkward and error prone (e.g. needing to escape quote marks and escape escapes).
Or is this already the poster child for why people create parsers based on grammars and move out of Regexp?

Categories

Resources