Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template literals in javascript [duplicate]

in javascript I can write the follow code:

response = {
    status: 1,
    data: {
        key : 2
    }
}
var result = `status is ${response.status}, data key is ${response.data.key}`
console.log(result);

the output is

status is 1, data key is 2

Is there any libs provide the way to do it in java, providing the following function?

String xxxFunction(Map map, String template)

please note the usage of ${response.data.key}, map in map

like image 549
fudy Avatar asked Aug 16 '18 09:08

fudy


People also ask

What are template literals in JavaScript?

Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.

What is ${} called in JavaScript?

${} is a placeholder that is used in template literals. You can use any valid JavaScript expression such as variable, arithmetic operation, function call, and others inside ${}. The expression used inside ${} is executed at runtime, and its output is passed as a string to template literals.

Can you concatenate template literals?

When you use regular template literals, your input is passed to a default function that concatenates it into a single string. An interesting thing is that you can change it by preceding the template literal with your function name that acts as a tag. By doing it, you create a tagged template.

What are the advantages of using template literals?

In addition to its syntactical differences there are two very specific advantages to using template literals: Multi-line strings: A single string can span two or more lines. Expression Interpolation: Javascript variables and expressions can be inserted directly in the string.


2 Answers

You can make use of String.format

String template = "status is %s, data key is %s"
String result = String.format(template, status, key);
like image 84
pvpkiran Avatar answered Sep 22 '22 12:09

pvpkiran


You can try StrSubstitutor from Apache common text

 Map valuesMap = HashMap();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumps over the ${target}. ${undefined.number:-1234567890}.";
 StrSubstitutor sub = new StrSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);

You can find a download link / dependency here

like image 23
Mạnh Quyết Nguyễn Avatar answered Sep 19 '22 12:09

Mạnh Quyết Nguyễn