|
| 1 | +/* |
| 2 | +INFO: String Object |
| 3 | +String is a build-in-object that allows you to work with text. |
| 4 | +*/ |
| 5 | + |
| 6 | +/* |
| 7 | +A string can be created using: |
| 8 | +- String literal: "hello" |
| 9 | +- String constructor: new String("hello") (not recommended) |
| 10 | +*/ |
| 11 | +let str1 = "hello"; |
| 12 | +let str2 = new String("hello"); |
| 13 | + |
| 14 | +// Properties of String |
| 15 | +let str = "hello"; |
| 16 | +str.length; // 5 |
| 17 | + |
| 18 | +// Methods of String |
| 19 | +// - Character Access |
| 20 | +str.charAt(index); // returns character at a position |
| 21 | +str.charCodeAt(index); // Unicode of character at position |
| 22 | +str.codePointAt(index); // Full Unicode code point (for emojis, etc.) |
| 23 | + |
| 24 | +// - Searching |
| 25 | +str.indexOf("h"); // finds position of first match |
| 26 | +str.lastIndexOf("l"); // finds position of last match |
| 27 | +str.includes("o"); // returns true if text if found |
| 28 | +str.startsWith("h"); // checks if string starts with given text |
| 29 | +str.endsWith("o"); // checks if string ends with given text |
| 30 | + |
| 31 | +// - Modify / Extract |
| 32 | +str.slice(0, 2); // extracts part of string |
| 33 | +str.substring(0, 2); // similar to slice but no negatives |
| 34 | +str.replace("a", "b"); // replaces first match |
| 35 | +str.replaceAll("a", "b"); // replaces all matches |
| 36 | +str.toUpperCase(); |
| 37 | +str.toLowerCase(); |
| 38 | +str.repeat(3); // repeats the string n times |
| 39 | +str.trim() && str.trimStart() && str.trimEnd(); // removes spaces |
| 40 | + |
| 41 | +// - Conversion |
| 42 | +str.split(" "); // converts string to array |
| 43 | +str.toString(); // returns string version |
| 44 | +str.valueOf(); // returns primitive value |
| 45 | +str.padStart(11, "*") && str.padEnd(12, "$"); // Pads string |
0 commit comments