Web development and Tech news Blog site. WEBISFREE.com

HOME > lodash

Exploring the lodash startsWith() Method

Last Modified : 03 Oct, 2023 / Created : 03 Oct, 2023
98
View Count
We will take a look at one of the methods in the lodash library, startsWith().




# Exploring the lodash startsWith() Method

This function can be used with strings, returning true if the starting character matches the condition and false otherwise. The simple syntax is as follows:


_.startsWith(string, target, position)

string // The entire string
target // The starting character to find
position // [Option] The starting position as a number value (Default. 0)

The last argument, position, represents the index where the string comparison should start, allowing for searches not necessarily from the first position. Let’s create some examples below to understand it better.


! Viewing startsWith() Exmaples

Here, by viewing examples, we can understand how it is actually utilized and applied.

let myStr = 'webisfree';
_.startsWith(myStr, 'w');
_.startsWith(myStr, 'w', 0);

// Result
true
true

The above example will return true because the starting character of the variable myStr is 'w'. Note that the third argument, position, is optional and defaults to 0 if not provided. @ Different Starting Position Now, let's check the result when it starts with 'i' instead of 'w'.
_.startsWith(myStr, 'i');

// Result
false

It returns false because it does not start with 'i'.


@ Changing Starting Position
Then, let’s change the starting position value and run the example again.
_.startsWith(myStr, 'i', 3);

// Result
true

As shown, it’s possible to set the starting position to wherever you want.


! Using startsWith() with Numbers


Numbers, not just characters, can also be used with startsWith().
_.startsWith(12345, 1);
_.startsWith(12345, 2);

// Result
true
false

The above execution returned true, and the result below returned false.


That’s all for exploring the lodash startsWith() method.
Perhaps you're looking for the following text as well?

Previous

[lodash] How to use the trim() function and examples

Previous

[lodash] Reverse the order of an array, using the reverse function