DEV Community

Cover image for JavaScript function which confirms the ending of a word
Cesare
Cesare

Posted on

JavaScript function which confirms the ending of a word

Here is the problem :

We want to create a function that takes two arguments, both strings, and tell us if the second argument is the end of the string or not.

For example, the first argument could be 'Cesare' and the second 'e' the function should give us back the boolean true.

Here the function

function confirmEnding(str, target) {

with the use of:

  • boolean;
  • the method slice();
  • the string.length property,

The function is created:

return str.slice(str.length - target.length) === target ;
}

explanation:

The method slice will take as argument one integer that gives the string index of the str. This integer is given by the difference of first - second argument length.

If then the given output of str.slice() is === to target we have true or false as result.

And is what we wanted.

function confirmEnding(str, target) {

  return str.slice(str.length - target.length) === target  ;
}

confirmEnding("Cesare", "e");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)