JS: String (basics)
What is string
String is a sequence of characters. (technically, it is sequence of 2 bytes of unicode utf-16 encoding, called “Code Unit”.)
Create string
// QUOTATION MARK quoted string console.log("my cat"); // my cat // s------------------------------ // APOSTROPHE quoted string console.log('my cat'); // my cat // s------------------------------ // template string. // can embed expressions console.log(`2 + 3 = ${2 + 3}`); // 2 + 3 = 5
String escape sequence
// with escape sequence console.log('john\'s cat'); // john's cat
String operations
// length console.log("abc".length); // 3 // s------------------------------ // slice console.log("01234".slice(1, 3)); // 12 // s------------------------------ // join console.log("aa" + "bb"); // aabb
Loop thru characters
Index of string
Many string methods take index (integer) as argument, or return a index.
Some string methods also allow negative index. Negative index usually means count from right to left, starting at the end of string, but some method treat negative index as 0.
a b c d e f g 0 1 2 3 4 5 6 7
a b c d e f g -7 -6 -5 -4 -3 -2 -1 0
The most intuitive way to understand index is to think of index as between the chars. Index 0 is before first character. Index 1 is after first character. Index -1 is the place between last character and second last character.
String type
String is one of Value Types.