Skip to content

Algorithm Confirm The Ending

Quincy Larson edited this page Aug 20, 2016 · 1 revision

Algorithm Confirm the Ending

🏁 Problem Explanation:

The function is a whole Boolean operation. You need to return true if the first argument ends with the second argument. This means that for the problem script, it should return true for the confirmEnding('Bastian', 'n'); case.

Relevant Links

💬 Hint: 1

Take a look at how substr() works. You will be trying to get the last Nth characters.

try to solve the problem now

💬 Hint: 2

To get the Nth-to-Last character you will use length() and turn it into a negative number.

try to solve the problem now

💬 Hint: 3

Check that you have the proper syntax and that you use === to compare.

try to solve the problem now

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solution ahead!

🔰 Basic Code Solution:

function confirmEnding(str, target) {
  return str.substr(-target.length) === target;
}

🚀 Run Code

Code Explanation:

The substr() method returns the characters in a string beginning at the specified location through the optional specified number of characters. substr operates through the end of the string if the second optional parameter is not specified. substr() calculates the index of first matching character from the string's end if the specified location is negative. Using the - operator in front of target.length makes it negative.

We use the method substr() with the negative value of target's length to extract the ending segment of str of the same size as target, compare it to target, and then return the value of this boolean expression.

🏆 Credits:

If you found this page useful, you can give thanks by copying and pasting this on the main chat:

Thanks @Rafase282 for your help with Algorithm: Confirm the Ending

📋 NOTES FOR CONTRIBUTIONS:

  • ⚠️ DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. 🚥
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See 👉 Wiki Challenge Solution Template for reference.

Clone this wiki locally