Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

JavaScript - String

Back


String


Immutalbe

Escape Character

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.";

String: Multiple lines text

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!";

Strings as Objects

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

String Length: length

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;

Template Literals

var text = `Hello World!`;
var text = `He's often called "Johnny"`;
var text = `The quick
brown fox
jumps over
the lazy dog`;
var firstName = "John";
var lastName = "Doe";

var text = `Welcome ${firstName}, ${lastName}!`;
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>`;

TOP