Basic String Operations
Explore fundamental string operations in JavaScript including slicing, concatenation, repeating, splitting, and joining. Understand the immutability of strings and analyze the time and space complexity of each operation. This lesson helps you build efficient string algorithms by recognizing the costs associated with common string manipulations.
Now that we’ve established that strings are immutable and that any apparent modification produces a new string rather than altering the original, the next step is to build familiarity with the operations that are actually available on strings. These operations form the practical foundation of string algorithm implementation. Each one has a defined behavior and a measurable cost, and understanding both is essential before moving on to writing algorithms that use them.
Slicing: Extracting part of a string
Slicing is the operation of extracting a contiguous portion of a string. The extracted portion is called a substring, and it is returned as a new string. The original string remains unchanged.
In JavaScript, slicing uses the following syntax:
s.slice(start, end)
The result contains all characters from the start index up to, but not including, the end index. Consider the following example:
In this example, s.slice(0, 5) extracts the first five characters, and s.slice(6, 11) extracts the last five. The character at the end index is never included in the result.
Now, let’s look at the following visualizer for a better understanding of slicing in strings:
Omitting start and end in slicing
If the start or end value is omitted, JavaScript slice() uses default values:
When the
startindex is omitted, the slice begins at the first character.When the
endindex is omitted, the slice extends to the last character.When both are omitted, the entire string is returned as a new copy.
Complexity analysis of slicing
Producing a slice of length