Strings as Arrays
Video
JavaScript Notes
JavaScript
//treating Strings like Arrays
let log = console.log;
let str = "Ragnar Lothbrok";
// to split the string
let arr = str.split(""); //splits string into an array
let arr2 = Array.from(str); //splits any iterable and turns it into an array
log(arr, arr2);
// to target particular characters
log(arr[0], arr2[1]);
log(str[0], str[1]);
log(str.charAt(0), str.charAt(1));
// concat() - combine two arrays OR combine two strings
str.concat("asdf");
arr.concat(arr2);
str.indexOf("g") //2
str.lastIndexOf("g") // 3
arr.indexOf("R"); //0
str.includes("R") //true
arr.includes("R") //true
slice(begin, end) // - extract / shallow copy of part of the array or string
str.slice(1, 3) // agn
arr.slice(1, 3) // ["a", "g", "n"]
// for...of needs and iterable, but both arrays and strings are iterable
for (let char of str) {
log(char);
}
for (let char of arr) {
log(char);
}
Feedback
Submit and view feedback