JavaScript String and Array Method Cheatsheet: A Comprehensive Guide with Examples

JavaScript is a popular programming language used for web development. It provides a variety of built-in string and array methods that make it easier to manipulate and work with strings and arrays.

In this blog, we will provide a cheatsheet of commonly used JavaScript string and array methods, along with code examples to illustrate their usage.

JavaScript String and Array Method Cheatsheet: A Comprehensive Guide with Examples
Priyanka Parmar
Mar 17, 2023
Development

JavaScript String Methods:

1. indexOf(): Returns the index of the first occurrence of a specified substring within a string.

Example:

const str = "Hello World";

const index = str.indexOf("World");

console.log(index); // Output: 6

2. slice(): Returns a portion of a string.

Example:

const str = "Hello World";

const result = str.slice(6);

console.log(result); // Output: "World"

3. toUpperCase(): Converts a string to uppercase.

Example:

const str = "Hello World";

const result = str.toUpperCase();

console.log(result); // Output: "HELLO WORLD"

JavaScript Array Methods:

1. push(): Adds one or more elements to the end of an array.

Example:

const arr = ["apple", "banana"];

arr.push("orange");

console.log(arr); // Output: ["apple", "banana", "orange"]

2. pop(): Removes the last element of an array.

Example:

const arr = ["apple", "banana", "orange"];

arr.pop();

console.log(arr); // Output: ["apple", "banana"]

3. splice(): Changes the content of an array by removing or replacing existing elements and/or adding new elements.

Example:

const arr = ["apple", "banana", "orange"];

arr.splice(1, 1, "grape");

console.log(arr); // Output: ["apple", "grape", "orange"]

Conclusion:

In this blog, we have provided a cheatsheet of commonly used JavaScript string and array methods, along with code examples to illustrate their usage. Understanding these methods is essential for efficient and effective JavaScript programming. By using these methods, you can make your code more concise and easier to read, ultimately improving your productivity as a developer.