About Lesson
We will address the following Topics
ToggleIntroduction to Strings and Arrays
String Methods
Assuming all readers have a basic understanding of arrays and strings, we won’t dwell on those concepts. Instead, here’s a concise list of frequently used string methods:
charAt(index)
: Retrieves a character at a specific index in a string.
const text = "Hello, World!"; const character = text.charAt(7); // Returns 'W'
charCodeAt
: used to retrieve the Unicode value (integer representation) of a character at a specified index within a string.
const text = "Hello, World!"; const index = 7; // Index of the character 'W' const charCode = text.charCodeAt(index); // 87
length
: Provides the length of a string.
const text = "Sample Text"; const length = text.length; // Returns 11
toUpperCase()
andtoLowerCase()
: Converts text to uppercase or lowercase.
const text = "Convert Me"; const upper = text.toUpperCase(); // Returns "CONVERT ME" const lower = text.toLowerCase(); // Returns "convert me"
concat(str2)
: Combines two strings into one.
const str1 = "Hello, "; const str2 = "World!"; const combined = str1.concat(str2); // Returns "Hello, World!"
indexOf(substring)
: Identifies the index of the first occurrence of a substring.
const text = "This is a sample text."; const index = text.indexOf("sample"); // Returns 10
substring(startIndex, endIndex)
: Extracts a section of a string, starting at thestart
index(inclusive) and ending at theend
index (exclusive).
const text = "Extract this part."; const substring = text.substring(8, 18); // Returns "this part"
substr(start, length)
: extracts characters from the string, starting at thestart
index and continuing for a specifiedlength
of characters. It allows you to use a negativestart
index, which counts from the end of the string.
const text = "Hello, World!"; const sub = text.substr(7, 5); // Returns "World"
split(separator)
: Divides a string into an array of substrings using a separator.
const text = "Apple, Banana, Cherry"; const fruits = text.split(", "); // Returns ["Apple", "Banana", "Cherry"]
trim()
: Eliminates excess whitespace from the string’s beginning and end. Also, there are methodstrimStart()
,trimEnd()
const text = " Trim me! "; const trimmed = text.trim(); // Returns "Trim me!"
replace(oldValue, newValue)
: Substitutes instances of a specific substring with a new one.
const text = "Replace these words."; const newText = text.replace("these", "those"); // Returns "Replace those words."
padStart(maxLength, fillString)
: is used to pad the beginning (left side) of a string to reach the specifiedmaxLength
. It adds characters fromfillString
to the left of the original string until it reaches the desired length.
const text = "123"; const paddedText = text.padStart(5, "0"); // Returns "00123"
padEnd(maxLength, fillString)
: is used to pad the end (right side) of a string to reach the specifiedmaxLength
. It appends characters fromfillString
to the right of the original string until it reaches the desired length.
const text = "123"; const paddedText = text.padEnd(5, "*"); // Returns "123**"
String Search Methods
Below is a concise list of commonly used string search methods, along with examples of how to use them.
indexOf(substring)
: returns the index of the first occurrence of a specifiedsubstring
within the string. If the substring is not found, it returns-1
.
const text = "Hello, World!"; const index = text.indexOf("World"); // Returns 7
lastIndexOf(substring)
: returns the index of the last occurrence of a specifiedsubstring
within the string. If the substring is not found, it returns-1
.
const text = "Hello, World! Hello!"; const index = text.lastIndexOf("Hello"); // Returns 13
search(regexp)
: searches for a specified regular expression (regexp
) within the string and returns the index of the first match. If no match is found, it returns-1
.
const text = "Hello, World!"; const index = text.search(/world/i); // Returns 7 (case-insensitive search)
match(regexp)
: searches for a specified regular expression (regexp
) within the string and returns an array of matches found. If no matches are found, it returnsnull
.
const text = "Hello, 123 World 456!"; const matches = text.match(/\d+/g); // Returns an array: ["123", "456"]
includes(substring)
: checks if the string contains the specifiedsubstring
. It returnstrue
if the substring is found andfalse
if not.
const text = "Hello, World!"; const hasWorld = text.includes("World"); // Returns true
startsWith(substring)
: checks if the string starts with the specifiedsubstring
. It returnstrue
if the string begins with the substring andfalse
if not.
const text = "Hello, World!"; const startsWithHello = text.startsWith("Hello"); // Returns true
endsWith(substring)
: checks if the string ends with the specifiedsubstring
. It returnstrue
if the string concludes with the substring andfalse
if not.
const text = "Hello, World!"; const endsWithWorld = text.endsWith("World!"); // Returns true
Array Methods
Below is a concise list of commonly used array methods, along with examples of how to use them:slice() 🍰
: Easily extract specific portions of an array while keeping the original array intact.
const originalArray = [1, 2, 3, 4, 5]; const slicedArray = originalArray.slice(1, 4); // Returns [2, 3, 4]
splice() ✂️
: Dynamically remove or insert elements into an array, allowing on-the-fly modifications.
const originalArray = [1, 2, 3, 4, 5]; originalArray.splice(2, 1); // Removes '3' from the array
find() 🔍 and findIndex() 🔍
: Easily locate elements meeting specific conditions and find their indices.
const numbers = [10, 20, 30, 40, 50]; const result = numbers.find(num => num > 25); // Returns 30
some() 👀 and every() 👁️
: Validate if some or all elements in an array meet specified criteria.
const numbers = [10, 20, 30, 40, 50]; const someAbove35 = numbers.some(num => num > 35); // Returns true
flat() ➡️
: Simplify complex arrays by flattening them for efficient data processing.
const nestedArray = [1, [2, 3], [4, [5]]]; const flatArray = nestedArray.flat(2); // Returns [1, 2, 3, 4, 5]
flatMap() ➡️🔄
: Combine mapping and flattening in a single method for enhanced array transformations.
const numbers = [1, 2, 3]; const doubled = numbers.flatMap(num => [num, num * 2]); // Returns [1, 2, 2, 4, 3, 6]
sort() 🔄
: Organize arrays for improved data presentation and organization.
const fruits = ["banana", "apple", "cherry"]; fruits.sort(); // Arranges the array alphabetically
fill() 🎨
: Refresh parts of an array with new values, suitable for quick updates and resets.
const numbers = [1, 2, 3, 4, 5]; numbers.fill(0, 2, 4); // Replaces elements from index 2 to 3 with '0'
from() 🔄
: Create arrays from iterable objects, offering flexibility in data manipulation.
const iterable = 'hello'; const charArray = Array.from(iterable); // Converts a string into an array of characters
concat() and join()
: Seamlessly merge arrays and convert them to strings, enhancing data handling capabilities.
const array1 = [1, 2]; const array2 = [3, 4]; const mergedArray = array1.concat(array2); // Merges the two arrays const joinedString = mergedArray.join(', '); // Converts the merged array into a comma-separated string
Object Methods
Objects serve as the fundamental components of JavaScript, and it’s essential to have a grasp of efficient ways to work with them. We’ll delve into key object methods that will enhance your programming skills.keys(obj)
: returns an array of a given object’s own enumerable property names.
const person = { name: "John", age: 30, gender: "Male" }; const propertyNames = Object.keys(person); // Returns ["name", "age", "gender"]
values(obj)
: returns an array of a given object’s own enumerable property values.
const person = { name: "John", age: 30, gender: "Male" }; const propertyValues = Object.values(person); // Returns ["John", 30, "Male"]
hasOwnProperty(prop)
: checks if a specific property exists on the object and returnstrue
orfalse
.
const person = { name: "John", age: 30, gender: "Male" }; const hasName = person.hasOwnProperty("name"); // Returns true
assign(target, source)
: copies the values of all enumerable own properties from one or more source objects to a target object.
const target = { a: 1 }; const source = { b: 2 }; Object.assign(target, source); // target is now { a: 1, b: 2 }
freeze(obj)
: makes an object immutable by preventing the addition, deletion, or modification of its properties.
const person = { name: "John" }; Object.freeze(person); // You can't modify or add properties to 'person'
defineProperty(obj, prop, descriptor)
: defines a new property or modifies an existing property’s attributes for an object.
const person = { name: "John" }; Object.defineProperty(person, "age", { value: 30, writable: false }); // 'age' property is now read-only
toString()
: converts an object to a string representation.
const person = { name: "John", age: 30 }; const str = person.toString(); // Returns "[object Object]"
entries(obj)
: returns an array of an object’s own enumerable property[key, value]
pairs.
const person = { name: "John", age: 30 }; const propertyEntries = Object.entries(person); // Returns [["name", "John"], ["age", 30]]
fromEntries(iterable)
: transforms an iterable of[key, value]
pairs into an object.
const entries = [["name", "John"], ["age", 30]]; const person = Object.fromEntries(entries); // Creates an object { name: "John", age: 30 }