String Indexing
We sometimes need to access individual characters in a string. The characters in a string can be located using their index
value, which represents their position in the string. Enclosing the index in square brackets will select a single character from a string:
string[index number]
Characters are indexed from left to right, starting from the position 0
, not 1
! Blank spaces are also counted as characters.
let str = "Hello";
console.log(str[0]); // H
console.log(str[2]); // l
Note that strings are immutable, we can not change any character in a string, but we can create new strings.
The slice() Method
To get a substring, use: str.slice()
slice(start, end)
extracts a part of a string and returns a new string including the part of the string from index start
to index end
(excluding end
).
If there is only one argument like in slice(start)
, then slice goes till the end of the string.
let food ='blueberry muffin';
let n = food.slice(4,9);
console.log(n); // berry (slice from index 4 to 9, excluding 9)
let r = food.slice(4);
console.log(r); // berry muffin (slice from index 4 to the end)
To understand how slicing works, think of an index as a pointer between characters in a string:
+---+---+---+---+---+---+---+---+---+---+
| J | a | v | a | S | c | r | i | p | t |
+---+---+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7 8 9 10
0 is before the first element, slice(start, end)
includes everything between the two indices.