How to Confirm the Ending of a  String in Javascript

How to Confirm the Ending of a String in Javascript

I could remember learning a new programming language some years back. Things were very abstract, all I knew how to do was to use the print keyword of the language to play around with texts. "Hello, world" statement was a sure keyboard play for people like myself. This being my first article, I would greet you with the statement "Hello, world". Dry joke ehn?

In this article, I will be taking you through the process of confirming the end of a string. Given a parent string and a target string that may or may not be the end of the given parent string. This challenge is a part of the Freecodecamp Basic Algorithm Scripting Challenge.

This solution is by no way the only existing solution, There are many approaches to solving this problem, this one is just one of them. There is a saying:

Nobody learns without getting it wrong.

After a whole lot of trial and error, I was able to arrive at a simple, yet easy-to-understand solution. Feel free to also post your solution someone else might benefit. In preparation for this tutorial, an understanding of the ES 2015 version of javascript is nice to have. Though, not the prerequisite for this tutorial.

Refresher

Before we start, let us quickly brush through some Javascript String methods, that will make you adapt to the flow of this tutorial. Without doubts, there are many Javascript String Methods.

In this tutorial, we will looking at: str.substring() and str.lastIndexOf() methods.

Let's start with str.substring(),

According to MDN,

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

Te help to grab it easily, lets quickly run through a code:

const str = 'Gorilla';

let substring1 = str.substring(1, 3);

console.log(substring1);

const str = 'Gorilla';

We declare a string variable str and assigned it a value of 'Gorilla'.

let substring1 = str.substring(1,3)

The above code extracts a substring from string 'str' starting from index 1 and stops at index 2. Substring will extract the string up to the second index, but not including it. It then stores the extracted string into a variable named 'substring1'.

So, the above code will return the string 'or'.

I guess you now understand how substring works.

The next string method we will be looking at is String.lastIndexOf().

From MDN,

The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.

I feel you'll get it better with examples, we'll explain it in a moment.

const paragraph = 'You are an awesome developer';

let searchTerm = 'an';

console.log(`The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(searchTerm)}`);

const paragraph = 'You are an awesome developer';

We declare a variable named 'paragraph', which stores the string 'You are an awesome developer',

Also a variable named 'searchTerm' was declared, which stores the string whose index we are searching for.

paragraph.lastIndexOf(searchTerm)

Using the above code, lastIndexOf() searches for the last occurrence of the string 'searchTerm' in the string 'paragraph' and returns its index.

So, the above snippet will return "The index of the first "an" from the end is 8".

Back to the challenge we have:

Let's get our hands dirty:


function confirmEnding(str, target) {
  //Get the position (index) of the target in the given string (str)
  const targetPosOnString = str.lastIndexOf(target);
  //Extract a substring of the given starting from the given index (targetPosOnString)
  const extractedString = str.substring(targetPosOnString);
  //Check if the extracted string is the same as the target
  if(extractedString === target){
    return true;
  }
  return false;
}

confirmEnding("mountain", "tain");

Explanation

  • We declared a function name confirmEnding which takes a string 'str' and the target value 'target' as an argument.
  • In the function 'confirmEnding', we declared a variable name 'targetPosOnString',

const targetPosOnString = str.lastIndexOf(target);

It stores the index of the last occurrence of the target

  • We also declared a variable 'extractedString'

    const extractedString = str.substring(targetPosOnString);

    It extracts a substring from the given string 'str', starting from the target position on the string.

Confirming the End

It confirms the end by checking if the extracted string is the same as the target string:

if(extractedString === target){
    return true;
 }

Testing if it works

Let's call the confirmEnding string:

confirmEnding("mountain", "tain");

The above code returns true since the string 'mountain' was ended by the string 'tain'.

Conclusion:

There are a lot of ways to solve a problem, feel free to drop your comments and solutions , so that we can improve and also learn more.