Create JavaScript Strings
In JavaScript, strings are created by surrounding them with quotes. There
are three ways you can use quotes.
Single quotes: 'Hello'
Double quotes: "Hello"
Backticks: `Hello`
For example,
//strings example
const name = 'Peter';
const name1 = "Jack";
const result = `The names are ${name} and ${name1}`;
Single quotes and double quotes are practically the same and you can use
either of them.
Backticks are generally used when you need to include variables or
expressions into a string. This is done by wrapping variables or
expressions with ${variable or expression} as shown above.
You can also write a quote inside another quote. For example,
const name = 'My name is "Peter".';
However, the quote should not match the surrounding quotes. For
example,
const name = 'My name is 'Peter'.'; // error
JavaScript is Case-Sensitive
JavaScript is case-sensitive. That means in JavaScript, the lowercase and
uppercase letters are treated as different values. For example,
const a = 'a';
const b = 'A'
console.log(a === b); // false
In JavaScript, a and A are treated as different values.
JavaScript Multiline Strings
To use a multiline string, you can either use the + operator or
the \ operator. For example,
// using the + operator
const message1 = 'This is a long message ' +
'that spans across multiple lines' +
'in the code.'
// using the \ operator
const message2 = 'This is a long message \
that spans across multiple lines \
in the code.'
JavaScript String Length
To find the length of a string, you can use built-in length property. For
example,
const a = 'hello';
console.log(a.length); // 5
JavaScript Strings are immutable
In JavaScript, strings are immutable. That means the characters of a string
cannot be changed. For example,
let a = 'hello';
a[0] = 'H';
console.log(a); // "hello"
However, you can assign the variable name to a new string. For example,
let a = 'hello';
a = 'Hello';
console.log(a); // "Hello"