JavaScript Guide: Strings and Commonly Used Methods
Strings are one of the most commonly used data types in JavaScript. A string is a sequence of characters used to represent text, and JavaScript provides a rich set of built-in methods to manipulate strings efficiently.
Understanding JavaScript Strings
Strings in JavaScript are immutable, meaning that once a string is created, it cannot be altered directly. Any method applied to a string will return a new string rather than modifying the original.
Here, we discuss 15 commonly used string methods in JavaScript, their internal working, time complexity, and space complexity.
charAt(index)
Returns the character at the specified index in a string.
concat(str1, str2, ...)
Combines two or more strings into one.
includes(substring)
Checks if the string contains the specified substring.
indexOf(substring)
Returns the first index where the substring appears, or -1 if not found.
lastIndexOf(substring)
Returns the last index where the substring appears, or -1 if not found.
replace(substring, newSubstring)
Replaces the first occurrence of a specified substring.
replaceAll(substring, newSubstring)
Replaces all occurrences of a specified substring.
slice(start, end)
Extracts a section of a string between the specified indices.
split(separator)
Divides the string into an array of substrings based on a specified separator.
substring(start, end)
Extracts characters from the start index to, but not including, the end index.
toLowerCase()
Converts all characters to lowercase.
toUpperCase()
Converts all characters to uppercase.
trim()
Removes whitespace from both ends of a string.
trimStart()
Removes whitespace from the start of a string.
trimEnd()
Removes whitespace from the end of a string.
This guide provides an understanding of each method’s purpose, internal working, and the time and space complexity involved. These foundational methods are essential for string manipulation tasks in JavaScript.