Javascript day 2

Still with strings today.

Character Access

We can access a specific character in a string by using square brackets like this: string[0]; We get the first character.

Combining it with Length

Use the length property to get the last character, i.e.,

const language = "JavaScript";
language[language.length - 1]; // gets "t"
// language[language.length]; // will be undefined

The .at(index) Method

This makes life a little bit easier compared to using .length.

const language = "JavaScript";
language.at(0); // "J"
language.at(1); // "a"
language.at(2); // "v"
language.at(-1); // "t"
language.at(-2); // "p"

Substrings

The substring method is used when we want to get a few characters from a string. Let's have a look at the signature of substring.

someString.substring(indexStart, indexEnd)
// indexStart: the position of the first character you'd like to include
// indexEnd: the position of the first character you'd like to ignore

The indexEnd parameter is optional, which means if we omit it, it will assume indexEnd to be the same as the string length.

const language = "JavaScript";
language.substring(2, 4); // "va"
language.substring(4); // "Script"

Note: Do not use .substr as it's deprecated.

Plus Operation

The + (plus sign) can be used with strings as well.

let prefix = "Mr.";
let name = "Walnut";
let string = prefix + " " + name; // "Mr. Walnut"

+= Operator

let name = "Walnut";
name = name + " is cool";
console.log(name); // "Walnut is cool"
// same as
let name = "Walnut";
name += " is cool";
console.log(name); // "Walnut is cool"

Template Strings

By using backticks (``) instead of single or double quotes, we can create strings that support interpolation and multiline content.

Interpolation

This is a powerful concept. We can include variables in our string!

let language = "JavaScript";
`I am learning ${language}`; // "I am learning JavaScript"