Strings - methods Flashcards
length:
let str = “Hello, world!”;
console.log(str.length); // outputs 13
charAt(index):
let str = “Hello, world!”;
console.log(str.charAt(0)); // outputs “H”
substring(start, end):
let str = “Hello, world!”;
console.log(str.substring(0, 5)); // outputs “Hello”
he start argument is the index of the first character to include in the returned string, and the end argument is the index of the first character to exclude
substr(start, length):
let str = “Hello, world!”;
console.log(str.substr(7, 5)); // outputs “world”
The substr(start, length) method returns a part of the string starting at the specified start index (position) and extending for the specified number of characters.
slice(start, end):
let str = “Hello, world!”;
console.log(str.slice(7, 12)); // outputs “world”
The start argument is the index of the first character to include in the returned string, and the end argument is the index of the first character to exclude.
indexOf(searchValue, fromIndex):
let str = “Hello, world!”;
console.log(str.indexOf(“world”)); // outputs 7
lastIndexOf(searchValue, fromIndex):
let str = “Hello, world! world”;
console.log(str.lastIndexOf(“world”)); // outputs 13
includes(searchString, position):
let str = “Hello, world!”;
console.log(str.includes(“world”)); // outputs true
replace(searchValue, replaceValue):
let str = “Hello, world!”;
console.log(str.replace(“world”, “friend”)); // outputs “Hello, friend!”
split(separator, limit):
let str = “Hello, world!”;
console.log(str.split(“, “)); // outputs [“Hello”, “world!”]
The split(separator, limit) method splits a string into an array of substrings and returns the array. The separator argument is the string to use as the separator between each element in the returned array, and the optional limit argument is the maximum number of elements to include in the returned array.
regex methods (match, search, replace):
let str = “Hello, world!”;
console.log(str.search(/world/)); // outputs 7
let str = “Hello, world!”;
console.log(str.replace([/world/], “friend”)); // outputs “Hello, friend!”
let str = “Hello, world!”;
let result = str.match(/Hello, (\w+)/);
console.log(result); // outputs [“Hello, world”, “world”]
The match() method matches the string str against the regular expression /Hello, (\w+)/. The (\w+) capture group matches the word “world” in the string, and the result of the match is stored in an array result. The first element of the array result[0] is the entire matched string “Hello, world”, and the second element result[1] is the capture group “world”.