find star index of string javascript 1

find star index of string javascript

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, rawPos) {
            var pos = rawPos > 0 ? rawPos|0 : 0;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}

Here is what the above code is Doing:
1. It’s defining a function called `startsWith` on the `String` prototype.
2. It’s defining a property called `value` on that function.
3. It’s defining a function as the value of that property.
4. It’s defining a parameter called `search` for that function.
5. It’s defining a parameter called `rawPos` for that function.
6. It’s defining a variable called `pos` and assigning it the value of `rawPos` if `rawPos` is greater than 0, or 0 if it’s not.
7. It’s returning a boolean value that indicates whether the substring of the string that the function is called on, starting at `pos` and ending at `pos + search.length`, is equal to `search`.

So, if we call `”hello”.startsWith(“he”)`, the function will return `true`.

Now, let’s look at the code that’s defining the `endsWith` function:

Similar Posts