Table of contents
substring()
andsubstr()
are used to extract a portion of a string and return a new string, whileslice()
andsplice()
are used to extract a portion of an array and return a new array or modify the original array, respectively.In JavaScript, there are four methods that are commonly used to extract a portion of a string or an array:
substring
,substr
,slice
, andsplice
. While they may seem similar, they each have their own unique characteristics that set them apart from one another.substring
andsubstr
Both
substring
andsubstr
are string methods used to extract a portion of a string, but they have different ways of achieving this.substring
The
substring
method extracts a substring from a string and returns it as a new string. It takes two arguments: the starting index and the ending index.javascriptCopy codeconst str = 'hello world'; const result1 = str.substring(2, 6); console.log(result1); // "llo " const result2 = str.substring(2); console.log(result2); // "llo world"
If only the starting index is provided, the
substring
method extracts the substring from the starting index to the end of the string.substr
The
substr
method also extracts a substring from a string and returns it as a new string. However, instead of an ending index,substr
takes the length of the substring as its second argument.javascriptCopy codeconst str = 'hello world'; const result1 = str.substr(2, 4); console.log(result1); // "llo " const result2 = str.substr(2); console.log(result2); // "llo world"
If only the starting index is provided, the
substr
method extracts the substring from the starting index to the end of the string.slice
andsplice
While
substring
andsubstr
are string methods,slice
andsplice
are array methods used to extract a portion of an array. They work differently thansubstring
andsubstr
.slice
The
slice
method extracts a portion of an array and returns it as a new array. It takes two arguments: the starting index and the ending index.javascriptCopy codeconst arr = [1, 2, 3, 4, 5]; const result1 = arr.slice(2, 4); console.log(result1); // [3, 4] const result2 = arr.slice(2); console.log(result2); // [3, 4, 5]
If only the starting index is provided, the
slice
method extracts the portion of the array from the starting index to the end of the array.splice
The
splice
method also extracts a portion of an array, but it modifies the original array by removing or replacing elements. It takes at least two arguments: the starting index and the number of elements to remove. It can also take additional arguments to add new elements.javascriptCopy codeconst arr = [1, 2, 3, 4, 5]; const result1 = arr.splice(2, 2); console.log(result1); // [3, 4] console.log(arr); // [1, 2, 5] const result2 = arr.splice(2, 0, 6, 7); console.log(result2); // [] console.log(arr); // [1, 2, 6, 7, 5]
The
splice
method removes two elements starting from index 2 and returns them as an array. In the second example, it adds two new elements at index 2 and returns an