Free Code Camp – Basic Algorithm Scripting - Confirm The Ending
Tags: codenewbie, javascript, algorithms
Published: 2021-02-12 19:17:52

##**12/02/2021**

##**Introduction**

Just another blog of me typing out my thoughts as I attempt to create a basic algorithm for Free Code Camp. Here’s what I need to do:

> https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending

> Confirm the Ending

> Check if a string (first argument, str) ends with the given target string (second argument, target).

> This challenge can be solved with the .endsWith() method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.

> Starting point:

```javascript
function confirmEnding(str, target) {
  return str;
}

confirmEnding("Bastian", "n");
```

---

##**Begin!**

OK, I don't know what "JavaScript substring methods" there are off the top of my head so let's Google that:

> https://www.w3schools.com/jsref/jsref_substring.asp

> JavaScript String `substring()` Method

Oh, substring is a method. Maybe Free Code Camp meant to say method instead of methods because I was expecting a whole bunch of them. Anyway, this looks useful so let's test out the example:

```javascript
const testString = "thisIsATest";
const sub = testString.substring(0, 4);
console.log(sub);
```

> logs 'this'

So it looks like `.substring()` includes the first index given to it, but not the last.

There's also:

> https://www.w3schools.com/jsref/jsref_substr.asp

> JavaScript String `substr()` Method

Now I'm probably going need to do some reading to find out what the difference is.

> `.substring()` - "If either "start" or "end" is less than 0, it is treated as if it were 0."

Well that doesn't sound good. I was planning to use -1 to start at the end of the string. Let's check the other one:

> `.substr()` - "If start is negative, `substr()` uses it as a character index from the end of the string.""

Bingo! Let's give it a whirl:
```javascript
const testString2 = "thisIsATest";
const sub2 = testString2.substring(-1, 4);
console.log(sub2);
```

> logs 'this'

I didn't expect that. Time for some more reading:

> `.substr():`

> "If start is negative, `substr()` uses it as a character index from the end of the string.
> If start is negative or larger than the length of the string, start is set to 0"

I don't understand how these 2 sentences don't contradict each other. If I set the start index to be negative (-1), it will start from the end of the string but it will also set the start to '0'?

Whatever, I haven't got time to decipher The Da Vinci Code here. Let's just Google it:

> Search: javascript how to get characters at end of string

The first 3 results are to do with `.substring()` and `.substr()`. The 4th one is from stackoverflow.com so let's check that:

> https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string

> Question:
> How can I get last characters of a string

> Asked 9 years, 9 months ago

> Answer: As others have pointed out, use `slice(-5)` instead of `substr`

Looks like people didn't want to waste time trying to crack the code 9 years ago either. Let's give `.slice()` a test run:
```javascript
const testString3 = "thisIsATest";
const sub3 = testString3.slice(-1, 4);
console.log(sub3);
```
> logs &lt;empty string&gt;

OK, that was wishful thinking for that to work without checking how to use it. I better look up how to use it properly. Back to Google:

> Search: javascript slice

> Result: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

> "The `slice()` method returns a shallow copy of a portion of an array..."

Oh it's only for arrays? Did it say that on stackoverflow.com? Let's go back and look.

**Aaahhhhhhhhhhhhhhhhhhhhhhhhhhergneovnoeirnvor!!!**

I forgot to change `.substring()` to `.substr()` in the second example! Try again:
```javascript
const testString4 = "thisIsATest";
const sub4 = testString4.substr(-1, 4);
console.log(sub4);
```
> logs 't'

I wonder if that's the start or end of the string? It should be the end. Try again:
```javascript
const testString5 = "aThisIsATest";
const sub5 = testString5.substr(-1, 4);
console.log(sub5);
```
> logs 't'

OK, great. But why isn't the second parameter doing anything? I thought that was the length.

> "length - Optional. The number of characters to extract. If omitted, it extracts the rest of the string"

So why doesn't that work? Let's try some other numbers:
```javascript
const testString6 = "aThisIsATest";
const sub6 = testString6.substr(-1, 7);
console.log(sub6);
```
> logs 't'
```javascript
const testString7 = "aThisIsATest";
const sub7 = testString7.substr(-1, -7);
console.log(sub7);
```
> logs &lt;empty string&gt;

```javascript
const testString8 = "aThisIsATest";
const sub8 = testString8.substr(1, 7);
console.log(sub8);
```
> logs 'ThisIsA'

Well that one looks like progress. There must be a trick to make it work backwards from the end of the string.

> https://stackoverflow.com/questions/7447927/how-can-i-get-the-last-character-in-a-string

> How can I get the last character in a string?

> Asked 9 years, 5 months ago

All of the examples given seem to use 'string.length - 1'. I don't really know why since it already has the whole string so I thought that would be built in. Let's test it, but if it works, then JavaScript is garbage confirmed:
```javascript
const testString9 = "aThisIsATest";
const sub9 = testString9.substr(testString9.length - 1, 5);
console.log(sub9);
```
> logs 't'
```javascript
const testString10 = "aThisIsATest";
const sub10 = testString10.substr(
  testString10.length - 1,
  testString10.length - 5
);
console.log(sub10);
```
> logs 't'
```javascript
const testString11 = "aThisIsATest";
const sub11 = testString11.substr(testString11.length - 1, -5);
console.log(sub11);
```
> logs &lt;empty string&gt;

Good. I'm glad that didn't work. Now where was I? Looking up how to use `.slice()` I think:

> https://www.w3schools.com/jsref/jsref_slice_string.asp
> JavaScript String `slice()` method

Wait, I thought slice was for arrays? I guess I'll scroll up to see if I imagined it or not...

**OMG...**

> Search: javascript slice

> Result one: Array.prototype.slice() - JavaScript | MDN
> Result two: JavaScript String slice() Method - W3Schools

Well thanks for being better than w3schools at SEO, MDN! I almost believed `.slice()` was only for arrays! You can't expect people to look all the way down to the second search result of Google! Unbelievable!

Let's see if we can get `.slice()` working then:
```javascript
const testString12 = "aThisIsATest";
const sub12 = testString12.slice(1, 5);
console.log(sub12);
```
> logs 'This'
```javascript
const testString13 = "aThisIsATest";
const sub13 = testString13.slice(-1, 5);
console.log(sub13);
```
> logs &lt;empty string&gt;

Did I already try that? I feel like I already tried that.

---

So to sum it up so far... nothing works. And I don't even know if I'm taking the right approach if any of those methods did actually work. Let's just directly Google how to do it:

> Search: javascript get last 5 characters of string

> Result:

> https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string

> How can I get last characters of a string

> Asked 9 years, 9 months ago

Haven't I been here before? Oh right, I need to use string.length for some mysterious reason because giving it the numbers myself just isn't enough:
```javascript
const testString14 = "aThisIsATest";
const sub14 = testString14.slice(
  testString14.length - 1,
  testString14.length - 5
);
console.log(sub14);
```
> logs &lt;empty string&gt;
```javascript
const testString15 = "aThisIsATest";
const sub15 = testString15.slice(testString15.length - 1, 5);
console.log(sub15);
```
> logs &lt;empty string&gt;
```javascript
const testString16 = "aThisIsATest";
const sub16 = testString16.slice(testString16.length - 5);
console.log(sub16);
```
> logs 'ATest'

Hallelujah!!!

Why did that work though? Oh, I forgot to type one of the parameters. So will that work without using .length?
```javascript
const testString17 = "aThisIsATest";
const sub17 = testString17.slice(-5);
console.log(sub17);
```
> logs 'ATest'

What? So I don't need to give it an end point? I thought the website said it would return the rest of the string if you don't provide an end point?

> "length - Optional. The number of characters to extract. If omitted, it extracts the rest of the string"

Ahhh that was for `.substr()`. Here's the one for `.slice()`:

> "end - Optional. The position (up to, but not including) where to end the extraction. If omitted, `slice()` selects all characters from the start-position to the end of the string"

-------------------------------------------------

##**Starting The Algorithm**

OK great. That only took 17 attempts to get right. Now we can start the actual project.

...What did I have to do again? Let's close these 19 tabs and find out...

> Check if a string ends with another string

I can see `.slice()` being useful for that. Let's make a plan...

Let's give the strings names so it's easier to tell them apart:

> Check if a string (string1) ends with another string (string2)

1. Let's get the length of string2
2. Use that as the slice index on string1
3. Then I have 2 strings of equal length
4. ...And just do a strict equals on them? `===`

Will that work? Well it's the only plan I've got so let's go for it:
```javascript
function confirmEnding(str, target) {
  let targetLength = target.length;
  let slicedString = str.slice(-targetLength);
  if (slicedString === target) {
    return str;
  } else {
    return;
  }
}

confirmEnding("Bastian", "n");
```
Run it!

![Image showing an 'X' on all of the criteria because the code failed every test](https://dev-to-uploads.s3.amazonaws.com/i/t48cegzh5q7hsugtojee.png)

Nope. Failed every test.

Oh. It's supposed to return true or false. Why did it have "return str" in the original code it provided then? Try again:
```javascript
function confirmEnding(str, target) {
  let targetLength = target.length;
  let slicedString = str.slice(-targetLength);
  if (slicedString === target) {
    return true;
  } else {
    return false;
  }
}

confirmEnding("Bastian", "n");

```
Passed.

![Image shows that the algorithm has been completed and the user can move on to the next one](https://dev-to-uploads.s3.amazonaws.com/i/annnrrizexr0ta38czeq.png)

Bye bye.

--------------------------------------------

##**Thoughts**

Was typing all of this worth it? This took a lot longer than it would have if I didn't type out everything that I tried. Will this be helpful to anyone? I guess it might help me the next time I need to use `.slice()` but that's about it.

---------------------------------------------

##**Questions**

Why do so many examples use 'string.length -1' instead of just '-1' as parameters in `.substring()`, `.substr()`, `.slice()`? Is it because they're 9 years old and that's how things were done then?