Strings as Arrays
A string behaves like a read-only array of characters in several ways. It has a length, its characters can be read by index, it can be looped over with for...of, and it shares several method names with arrays. It is not an array, though, so array methods such as map() and reverse() need the string to be converted first.
Reading characters by index
Section titled “Reading characters by index”Square brackets read the character at a position, starting from 0. at() does the same and also accepts a negative position, which counts back from the end.
const word = 'kayak';
console.log(word[0], word[word.length - 1], word.at(-1));console.log(word.length);console.log(word[10]);This prints:
k k k5undefinedA position past the end gives undefined. The older charAt() method gives an empty string instead.
Characters cannot be changed
Section titled “Characters cannot be changed”Strings are immutable, so assigning to an index does nothing. In sloppy mode the assignment fails silently, and in strict mode it throws a TypeError. The example is a CommonJS script, which runs in sloppy mode like a browser’s classic script, with a strict function inside it.
const word = 'cat';word[0] = 'b';console.log(word);
(() => { 'use strict'; try { word[0] = 'b'; } catch (error) { console.log(`${error.name}: ${error.message}`); }})();This prints:
catTypeError: Cannot assign to read only property '0' of string 'cat'To change a character, build a new string, for example with 'b' + word.slice(1).
Methods strings share with arrays
Section titled “Methods strings share with arrays”slice(), indexOf(), includes(), at() and concat() exist on both strings and arrays, and work the same way.
const letters = 'abcde';const list = ['a', 'b', 'c', 'd', 'e'];
console.log(letters.slice(1, 3), list.slice(1, 3));console.log(letters.indexOf('c'), list.indexOf('c'));console.log(letters.includes('z'), list.includes('z'));console.log(letters.at(-1), list.at(-1));console.log(letters.concat('f'), list.concat('f'));This prints:
bc [ 'b', 'c' ]2 2false falsee eabcdef [ 'a', 'b', 'c', 'd', 'e', 'f' ]The difference is that a string’s indexOf() and includes() search for text of any length, while an array’s search for one element.
Converting a string to an array
Section titled “Converting a string to an array”There are three common ways to split a string into an array of characters. split('') splits into UTF-16 code units, so it breaks an emoji into two meaningless halves. Array.from() and the spread syntax both use the string’s iterator, which steps by code point and keeps each emoji whole.
const text = 'hi👍';
console.log(text.split(''));console.log(Array.from(text));console.log([...text]);This prints:
[ 'h', 'i', '\ud83d', '\udc4d' ][ 'h', 'i', '👍' ][ 'h', 'i', '👍' ]charCodeAt vs codePointAt explains code units and code points, and why even a code point is not always a whole visible character.
Using array methods on a string
Section titled “Using array methods on a string”Once a string is an array, any array method can be used, and join('') turns the result back into a string. A for...of loop needs no conversion, because strings are iterable.
const reversed = [...'stressed'].reverse().join('');console.log(reversed);
const vowels = [...'education'].filter((ch) => 'aeiou'.includes(ch));console.log(vowels.length);
for (const ch of 'ok👍') { console.log(ch);}This prints:
desserts5ok👍A for...in loop also works on a string, but it gives the indexes as strings rather than the characters, so for...of is the right choice.
Steve Griffith covers this topic in his video You Can Treat Strings Like Arrays.