JavaScript Utility Methods in Detail

Suriya Kumar
6 min readFeb 18, 2022

Javascript offers several utility methods, these methods are helpful for accomplishing routine programming tasks. In this article, we will look into some of the javascript utility methods with their parameters and return values.

Substring

In JavaScript, substring() is a string method that is used to extract a substring from a string, given start and end positions within the string.

From Mozilla:

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

Syntax:

String.substring(startIndex, endIndex);

startIndex

The index of the first character to include in the returned substring.

endIndex (Optional)

The index of the first character to exclude from the returned substring.

Description

substring() extracts characters from startIndex up to but not including endIndex. In particular:

  • If endIndex is omitted, substring() extracts characters to the end of the string.
  • If startIndex is equal to endIndex, substring() returns an empty string.
  • If startIndex is greater than endIndex, then the effect of substring() is as if the two arguments were swapped; See the example below.
  • Any argument value < 0 is treated as 0.

Any argument value that is less than 0 or greater than stringName.length is treated as if it were 0 and stringName.length, respectively.

Any argument value that is NaN is treated as if it were 0

Examples

const message = "JavaScript";
console.log(message.substring(0, 1)) // Displays 'J', argument will // get swap into message.substring(1, 0)
console.log(message.substring(11,8))// Display 'pt'
console.log(message.substring(8,11))// Display 'pt'
console.log(message.substring(8))// Display 'pt'

Substr //Deprecated

In JavaScript, substr() is a string method that is used to extract a substring from a string, given a start position and a length.

From Mozilla:

The substr() method returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.

Syntax

String.substring(startIndex, length);

startIndex

The position in the string where the extraction will start. The first position in the string is 0

Length

Optional. It is the number of characters to extract from a string. If this parameter is not provided, the substr() method will extract to the end of the string.

Description

substr() extracts length characters from a str, counting from the startIndex position.

  • If startIndex is a non-negative number, the index starts counting from the start of the string. Its value is capped at str.length - 1.
  • If startIndex is a negative number, the index starts counting from the end of the string. Its value is capped at -str.length.
  • Note: In Microsoft JScript, negative values of the startIndex argument are not considered to refer to the end of the string.
  • If length is omitted, substr() extracts characters to the end of the string.
  • If length is undefined, substr() extracts characters to the end of the string.
  • If length is a negative number, it is treated as 0.
  • For both startIndex and length, NaN is treated as 0.

Examples

const message = "JavaScript";
console.log(message.substr(0, 1)); // 'J'
console.log(message.substr(1, 0)); // ''
console.log(message.substr(-1, 1)); // 't'
console.log(message.substr(1, -1)); // ''
console.log(message.substr(-3)); // 'ipt'
console.log(message.substr(1)); // 'avaScript'

Slice

In JavaScript, slice() is a string method that is used to extract a substring from a string.

From Mozilla:

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

Syntax

String.substring(startIndex, endIndex);

startIndex

The position in the string where the extraction will start. The first position in the string is 0.

endIndex

Ending index of the selection (Exclusive) By default, it extracts till the end of the string. The character at this index will not be included.

Description

The slice() method returns a string that contains the extracted portion of string.

slice() extracts up to but not including endIndex. str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).

Negative numbers

If startIndex is negative, slice() begins extraction from str.length + startIndex(E.g. "test".slice(-2) returns "st")

If endIndex is negative, slice() begins extraction from str.length + endIndex(E.g, if endIndex is -2, it is treated as str.length - 2 and "test".slice(1, -2) returns "e")

Examples

const message = "JavaScript";
console.log(message.slice(1, 4)); // 'ava'
console.log(message.slice(4, -2)); // 'Scri'
console.log(message.slice(-3, -2)); // 'i' (10 - 3, 10 - 2) => (7, 8)
console.log(message.slice(7,8)); // 'i'

Splice

The splice() method returns an array by changing (adding/removing) its elements in place. It will modify the source array.

From Mozilla:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements

Syntax

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)

Start

The index at which to start changing the array.

If the start value is greater than the length of the array then nothing will get removed from the array. (E.g. [1,2,3,4,5,6,7].splice(9) returns "[]")

if the start value is in negative, then splice() begins extraction from array.length + startIndex(E.g. [1,2,3,4,5,6,7].splice(-2) returns "[6, 7]"original array will be "[1, 2, 3, 4, 5]")

deleteCount Optional

An integer indicating the number of elements in the array to remove from start.

If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted. However, it must not be omitted if there is any item1 parameter.

If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below)

item1, item2, ... Optional

The elements to add to the array, beginning from start.

If you do not specify any elements, splice() will only remove elements from the array.

Examples

let prime_numbers = [2, 3, 5, 7, 9, 11];// replace 1 element from index 4 by 13
let removedElement = prime_numbers.splice(4, 1, 13);
console.log(removedElement);
console.log(prime_numbers);

// Output: [ 9 ]
// [ 2, 3, 5, 7, 13, 11 ]

PadStart

The JavaScript String padStart() method pads the current string with another string to the start.

From Mozilla:

The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.

Syntax

str.padStart(targetLength, padString)

Parameters

  • targetLength — The length of the final string after current string has been padded. For targetLength < str.length, the string is returned unmodified.
  • padString (optional) — The string to pad with the current string. Its default value is " ".

Note: If padString is too long, it will be truncated from the end to meet targetLength.

Examples

let string = "CODE";

value1 = string.padStart(10);
console.log(value1); // " CODE"

value2 = string.padStart(10, "*");
console.log(value2); // "******CODE"

// long string is truncated
value3 = string.padStart(10, "ABCDEFGHIJKL");
console.log(value3); // "ABCDEFCODE"

PadEnd

The JavaScript String padEnd() method pads the current string with another string to the end.

From Mozilla:

The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string.

Syntax

str.padEnd(targetLength, padString)

Parameters

  • targetLength — The length of the final string after current string has been padded. For targetLength < str.length, the string is returned unmodified.
  • padString (optional) — The string to pad with the current string. Its default value is " ".

Note: If padString is too long, it will be truncated to meet targetLength.

Example

let string = "CODE";

value1 = string.padEnd(10);
console.log(value1); // "CODE "

value2 = string.padEnd(10, "*");
console.log(value2); // "CODE******"

// long string is truncated
value3 = string.padEnd(10, "ABCDEFGHIJKL");
console.log(value3); // "CODEABCDEF"

ReplaceAll

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement.The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

Syntax

str.replaceAll(pattern, replacement)

Parameters

  • pattern - either a substring or a regex that is to be replaced
  • replacement - the pattern is replaced with this replacement (can be either a string or a function)

Examples

const text = "Java is awesome. Java is fun.";

// passing a string as the first parameter
let pattern = "Java";
let new_text = text.replaceAll(pattern, "JavaScript");
console.log(new_text);

// passing a regex as the first parameter
pattern = /Java/g;
new_text = text.replaceAll(pattern, "JavaScript");
console.log(new_text);

At

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

This is not to suggest there is anything wrong with using the square bracket notation. For example array[0] would return the first item. However instead of using array.length for latter items; e.g. array[array.length-1] for the last item, you can call array.at(-1)

Syntax

at(index)

Parameters

  • index - The index (position) of the array element is to be returned. Supports relative indexing from the end of the array when passed a negative index; i.e. if a negative number is used, the element returned will be found by counting back from the end of the array.

Examples

const array1 = [5, 12, 8, 130, 44];let index = 2;console.log(array1.at(index)); // 8index = -2;console.log(array1.at(index)); // 130 at((arraylength - 2)) => (5-2) => position 3

Conclusion

This was a really long article and if you got this far well done! I hope you have found this useful. Thank you for reading and happy coding 😊.

--

--

Suriya Kumar

Senior Software Engineer at AngelOne #Javascript #ReactJS