Create a polyfill function for the string method endsWith().




JavaScript provides a string method called endsWith() that checks whether a string ends with a given substring, or not.

If it does, the method returns true, however, if it doesn't, the method returns false.

Consider the snippet below:


In the first statement, since 'Hello' ends with 'o', the method's call returns true. So is the case with the second statement. In the third statement however, 'Food' doesn't end with 'd', likewise we get false returned.

The method could optionally be provided with a second argument, that is the length of the main string to consider.

Consider the snippet below:

'Hello'.endsWith('o', 2)
'Hello'.endsWith('lo', 5)
'Food.'.endsWith('d', 4)

In the first statement, the second argument 2 makes searching limited to the substring 'He'. Since this (limited) string doesn't end with 'o', the method returns false.

In the second statement, the string considered in the searching is of length 5 i.e. the string 'Hello'. Since this string ends with 'lo', we get true returned.

In the third statement, the string considered in the searching is of length 4 i.e. the string 'Food'. Since this ends with the character 'd', we get true returned.

So this is how the method endsWith() works.

Now the thing is that endsWith() is not supported in earlier versions of Internet Explorer. This means that you'll have to create a polyfill for the method to use it in this browser.

In this exercise, you have to create a function endsWithPolyfill() that works exactly like the string method endsWith() as shown above.

Its syntax should be similar to the following:

function endsWithPolyfill(str, substr, length) {
    // code here

str should be the main string, substr should be the string to search for in str, and length should be the length of str to consider. It should default to the str.length.

If str (after considering length) ends with substr, the function should return true; or otherwise false.