Other Common String Operations
Explore fundamental string operations in JavaScript such as searching for substrings, comparing strings, converting case, and trimming spaces. This lesson helps you understand and apply these essential techniques to manipulate and evaluate strings efficiently in coding problems.
Knowing the basic string operations, such as finding the length, traversal, indexing, concatenation, slicing, and splitting, is an important start. Knowing additional string operations will better prepare you for a wider range of string algorithms. A problem may ask whether two strings are equal, whether one string starts with another, whether a smaller string appears inside a larger one, or how to form a new string from existing ones.
Searching
Searching refers to the operation of locating a character or a substring within a larger string. At a fundamental level, this is accomplished by scanning through the string and examining each position until the target is found or the end of the string is reached.
Checking for existence
The simplest form of search determines whether a substring exists anywhere within the string. In JavaScript, this is done using the includes() method.
The includes() method returns true if the substring is found and false otherwise.
Finding the position
When you need the exact position of the first occurrence, JavaScript provides the indexOf() method, which returns the starting index of the substring. If the substring is not present, indexOf() returns -1.
JavaScript's indexOf() does not raise an error when the substring is absent. It simply returns -1.
Counting occurrences
JavaScript does not provide a direct ...