This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.
Hello my fellow newbs! This will be one of the methods that you might call a “straight shooter”. Do you need to find out if your string starts in a certain way? Then look no further. StartsWith() method is here for you!
The startsWith() method determines whether a provided string begins with the characters of a specified string. The method returns true if the string begins with the characters and false if it doesn’t. Of course, the method is case sensitive.
The method has two parameters. First is mandatory and specifies the characters to be searched for at the start position.
The second parameter is optional and by default is equal to zero. It specifies the starting position at which to begin searching for the first parameter value.
Enough talk. Let’s code. Here is the first example.
const str = "Hello Dev Newbs! 😃";// starts with "Hello"
str.startsWith("Hello") // true// starts with "hello"
str.startsWith("hello") // false// starts with "Dev" - start searching at index 6
str.startsWith("Dev", 6) // true
As I mentioned before, this is quite a straightforward method. So don’t expect any serious blows under the belt. We need to take case sensitivity into consideration and the fact that we can start searching at different positions, other than the beginning of the string.
The only challenging aspect is to keep remembering that not all characters are made of one code unit. And this method works with code units, not code points. Keep that in mind and let’s have a look at this behavior in the second example.
const emotions = "😃😁😆😅🥰...so many emotions, man...😱😵🤐🤬😭😤";// takes positions at index 0 & 1
emotions.startsWith("😃", 0)˛ // true// "😃" consists of \uD83D (index 0) + \uDE03 (index 1)
emotions.startsWith("\uD83D", 1) // false
emotions.startsWith("\uDE03", 1) // true// takes positions at index 8 & 9
emotions.startsWith("🥰", 8) // true// starts at position 10
emotions.startsWith("...so many emotions", 10) // true// takes positions at index 37 & 38
emotions.startsWith("😱", 37) // true// "😱" is equal to \uD83D + \uDE31
emotions.startsWith("\uD83D\uDE31", 37) // true
As we see in the first case, we can check using characters consisting of multiple code units without any issues. We just need to specify the correct position.
Second case shows that we can use unicode values within the first parameter and it works just fine as long as we specify the correct position. We checked against the second code unit of the emoji, so we needed to start our comparison at that position. Once we did, the result was true.
Okay, that was our good guy method startsWith(). Not so adventurous, but reliable and always there for us to use.
As usual, thank you very much for your attention. I will see you soon with the next method.