All technological notes.
A JavaScript string is zero or more characters written inside quotes.
Strings are immutable
let str = "abc";
console.log(str[0]); // a
str[0] = "z";
console.log(str[0]); // a
console.log(str); // abc
//the string is not changed due to immutability.
str = "zyx";
console.log(str); // zyx
// here does not change the string, but change the value of variable. The old value is still in memory.
| Code | Result | Description |
|---|---|---|
\' |
’ | Single quote |
\" |
” | Double quote |
\\ |
\ | Backslash |
\b |
Backspace | |
\f |
Form Feed | |
\n |
New Line | |
\r |
Carriage Return | |
\t |
Horizontal Tabulator | |
\v |
Vertical Tabulator |
let text = 'We are the so-called "Vikings" from the north.';
let text = "It's alright.";
let text = "The character \\ is called backslash.";
document.getElementById("demo").innerHTML = "Hello Dolly!";
// The \ method is not the preferred method. It might not have universal support.
// Some browsers do not allow spaces behind the \ character.
document.getElementById("demo").innerHTML =
"Hello \
Dolly!";
document.getElementById("demo").innerHTML = "Hello " + "Dolly!";
Normally, JavaScript strings are primitive values, created from literals.
Strings can also be defined as objects with the keyword new.
new keyword complicates the code and slows down execution speed.Comparing two JavaScript objects always returns false.
let x = "John"; // x is a string
let y = new String("John"); // y is an object
x == y; // true
x === y; // false
let z = new String("John"); // z is an object
y == z; // false Comparing two JavaScript objects always returns false.
y === z; // false
length use the built-in length property
Example:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Template Literals use back-ticks (``) rather than the quotes (“”) to define a stringvar text = `Hello World!`;
var text = `He's often called "Johnny"`;
var text = `The quick
brown fox
jumps over
the lazy dog`;
Template literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation, automatic replacing of variables with real valuesVariable Substitutions: Template literals allow variables in stringsvar firstName = "John";
var lastName = "Doe";
var text = `Welcome ${firstName}, ${lastName}!`;
Expression Substitution: Template literals allow expressions in strings:let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
let header = "Templates Literals";
let tags = ["template literals", "javascript", "es6"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
html += `<li>${x}</li>`;
}
html += `</ul>`;