Strings as Rows of Characters

A string is a row of characters, and much of what you learned about arrays works on strings too:

const word = "bandana";

console.log(word[0]);
console.log(word.at(-1));
console.log(word.slice(0, 3));
console.log(word.slice(-3));
console.log(word.length);
console.log(word[99]);

Output:

b
a
ban
ana
7
undefined

The rules are the same as for arrays. Positions start at 0. .at(-1) reads from the end. slice(start, end) stops just before end, so slice(0, 3) gives the first three characters. A negative number in slice counts from the end. An index past the end gives undefined, not an error.

There is no separate type for a single character. word[0] is just a string of length 1, so you compare it like any other string:

<!-- continues -->
console.log(word[0] === "b");

Output:

true

One thing is different from arrays: you cannot change a string. Assigning to an index does nothing, and JavaScript does not report an error:

<!-- continues -->
word[0] = "B";
console.log(word);

const fixed = "B" + word.slice(1);
console.log(fixed);

Output:

bandana
Bandana

To "change" a string, build a new one. Here "B" is joined to everything after the first character.

To find where some text is, use indexOf. It returns the position of the first match, or -1 when the text is not there:

<!-- continues -->
console.log(word.indexOf("a"));
console.log(word.indexOf("dan"));
console.log(word.indexOf("z"));

Output:

1
3
-1

If you only need a yes or no answer, includes is easier to read. Use indexOf when you need the position, for example to cut a string at a certain character:

const email = "[email protected]";
const at = email.indexOf("@");
console.log(email.slice(0, at));
console.log(email.slice(at + 1));

Output:

alice
example.com

In the exercise, print the first and last character of a word, its first three and last three characters, and the position of the first "a".