Index
String Formatting Examples


String formatting is one of the first things we want to learn in any given programming language.

Js relatively recently started using the backtick character for string foratting. This backtick-bounded string is called a "template literal" or "template string", and it allows us to embed values into the string at locations we choose.

We dynamically embed the variable "nm" into the string, using the format ${expression}

let nm, s;
nm = 'Asha';
s = `Hello ${nm}, how are you?`;
prn(s);
We dynamically embed two variables "nm" and "age" into our template string.

let nm, age, s;
nm = 'Bruce';
age = 11;
s = `${nm} is ${age} years old.`;
prn(s);
We can also embed calculations into the template string like we do here with "${a*b}".

let a, b;
a = 10;
b = 5;
prn(`a is ${a} and b is ${b}`);
prn(`Their product is ${a*b}`);
Enclosing a string in backticks allows for a multi-line string (which is not allowed for single and double quoted strings).

const myMultiLineString =
`line 1
line 2
line 3
line 4`;
prn(myMultiLineString);

More Example Sources


Here are a couple (among many more) online related example sources: