Basic String Methods

Javascript strings are primitive and immutable: All string methods produces a new string without altering the original string.

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
 
let char = text.charAt(0);
//The method returns a UTF-16 code (an integer between 0 and 65535).
let char = text.charCodeAt(0);
// The `at()` method is supported in all modern browsers since March 2022:
// It allows the use of negative indexes while `charAt()` do not.
let letter = name.at(2);
// If no character is found, [ ] returns undefined,
// while charAt() returns an empty string.
let letter = name[2];
text[0] = "A"; // Gives no error, but does not work
// slice(start, end)      allow neg index
// substring(start, end)  values less than 0 are treated as 0
// substr(start, length)  second param specifies the length of the extracted part.
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
let part = str.substring(7, 13);
let part = str.substr(7, 6);
 
// `concat()` joins two or more strings:
let text3 = text1.concat(" ", text2);
 
let text = "5";
// Pad a string with "0" until it reaches the length 4:
let padded = text.padStart(4, "0");
 
let text = "Hello world!";
let result = text.repeat(2);
 
// The `replace()` method replaces **only the first** match
// If you want to replace all matches, use a regular expression with the /g flag set.
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
// To replace case insensitive, use a **regular expression** with an `/i` flag (insensitive):
let newText = text.replace(/MICROSOFT/i, "W3Schools");
// To replace all matches, use a **regular expression** with a `/g` flag (global match):
let newText = text.replace(/Microsoft/g, "W3Schools");
let text = text.replaceAll("cats", "dogs");
let text = text.replaceAll(/Cats/g, "Dogs");
 
// If the separator is omitted, the returned array will contain the whole string in index [0].
// If the separator is "", the returned array will be an array of single characters:
let x = text.split("|");
let x = text.split("");