0% found this document useful (0 votes)
6 views2 pages

Splice Slice Split Js

The document explains three JavaScript methods: splice, slice, and split. Splice modifies the original array by adding, removing, or replacing elements, while slice returns a shallow copy of a portion of an array or string without modifying the original. Split divides a string into an array of substrings based on a specified delimiter, also leaving the original string unchanged.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Splice Slice Split Js

The document explains three JavaScript methods: splice, slice, and split. Splice modifies the original array by adding, removing, or replacing elements, while slice returns a shallow copy of a portion of an array or string without modifying the original. Split divides a string into an array of substrings based on a specified delimiter, also leaving the original string unchanged.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

JavaScript Methods: splice, slice, and split

1. SPLICE (Array)

- Modifies the original array by adding, removing, or replacing elements.

- Syntax: array.splice(startIndex, deleteCount, ...itemsToAdd)

- Examples:

a. Remove elements:

let fruits = ["apple", "banana", "cherry", "date"];

fruits.splice(1, 2); // ["apple", "date"]

b. Add elements:

fruits.splice(1, 0, "banana", "cherry"); // ["apple", "banana", "cherry", "date"]

c. Replace elements:

fruits.splice(1, 1, "grape"); // ["apple", "grape", "cherry"]

2. SLICE (Array & String)

- Returns a shallow copy of a portion of the array or string as a new array.

- Does not modify the original array or string.

- Syntax: array.slice(startIndex, endIndex) OR string.slice(startIndex, endIndex)

- Examples:

a. Array slicing:

let fruits = ["apple", "banana", "cherry", "date"];

let slicedFruits = fruits.slice(1, 3); // ["banana", "cherry"]

b. String slicing:

let str = "Hello, World!";

let slicedStr = str.slice(7, 12); // "World"


3. SPLIT (String)

- Splits a string into an array of substrings based on a delimiter.

- Does not modify the original string.

- Syntax: string.split(delimiter, limit)

- Examples:

a. Basic splitting:

let sentence = "apple,banana,cherry,date";

let splitFruits = sentence.split(","); // ["apple", "banana", "cherry", "date"]

b. Splitting by character:

let str = "hello";

let characters = str.split(""); // ["h", "e", "l", "l", "o"]

Key Differences:

- SPLICE: Modifies the original array.

- SLICE: Returns a new array or string portion.

- SPLIT: Converts a string into a new array based on a delimiter.

You might also like