Two Ways To Check the Beginning of a String in JavaScript
Two simple strategies with code examples
The romantic image of development and programming is filled with complex algorithms, whiteboards, and walls of code. Below the clouds though are more mundane, yet still critical tasks such as string parsing.
Finding the start of a string, specifically determining if the start of a string is an exact value, is a common occurrence.
There are multiple strategies for this problem, we’ll be going over two of them in this article.
Use the .indexOf() Method
The indexOf() method is a member of the String class, returning an integer value. The integer represents the position of the first character in the original string, unless the substring is not found in which case a value of -1 is returned.
Going back to the original problem statement, if the indexOf() method returns a 0, then we know that the beginning of the String is our substring.my_string = "The greatest glory in living lies not in never falling, but in rising every time we fall";console.log(my_string.indexOf("The")); // returns 0
console.log(my_string.indexOf("glory")); // return 13
console.log(my_string.indexOf("world")); // returns -1
If you come from a Python background, the .indexOf() method may remind you of the .find() method.
Use the .startsWith() Method
If you’re looking for a simpler “yes/no” solution, then the appropriately named startsWith() method. Unlike indexOf(), the startsWith() method returns a true or a false depending on if the substring is found at the start of the base string.my_string = "The greatest glory in living lies not in never falling, but in rising every time we fall";console.log(my_string.startsWith("The")); // returns true
console.log(my_string.startsWith("glory")); // return false
console.log(my_string.startsWith("world")); // returns false
Although this strategy is more straightforward, unfortunately it is not as universally supported. The startsWith() method is supported starting with ECMAScript 2015, but the indexOf() method is universally supported.
Conclusion
The technique you choose will be dependent on a variety of factors such as:
- version support
- simplicity
- memory
If your application cannot guarantee a minimum version, the indexOf() method must be used. Conversely, if you need the simplest, most semantic and readable strategy, then startsWith() can’t be any more clear. Finally, if you’re like me write first, think later (I know, bad habit) then you’ll default to whichever method comes to mind first.
Please share your experiences, questions, and feedback below. Follow Code 85 for more plain language programming guides. Thanks for reading!