Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to check if a string ends with a given string in JavaScript

Abel Lifaefi Mbula

Problem statement

Write a JavaScript function that requires two parameters and returns true if the first parameter ends with the second one. Otherwise, it returns false. We may not use endsWith() method for this purpose.

Tests Cases

Here are some cases that we’ll need to test:

  • confirmEnding('Bastian', 'n') should return true.
  • confirmEnding("Connor", "n") should return false.
  • confirmEnding("He has to give me a new name", "name") should return true.
  • confirmEnding("Open sesam", "game") should return false.
  • confirmEnding("Abstraction", "action") should return true.

Logical thinking

Before diving deep into the implementation, let’s figure out how we can resolve this problem.

First, we need to make sure we only have one word as the first parameter. Therefore, we need to delete all the white spaces.

Next, we extract the last n characters to the length of the target. Now, we can check if the extracted string is equal to the target.

Example

Consider the string I am a test and the target string st.

Following the logical thinking stated above, here’s how we’ll proceed:

  1. Delete all the spaces, so the string becomes Iamatest.
  2. The length of the target string is 2.
  3. The last two characters are st (n characters).
  4. Comparison st == st.
  5. Output will be true.

First, let’s try to implement this in pseudocode, and then in JavaScript.

Pseudocode

confirmEnding(str, target)
   Set newStr to str without spaces
   Set subStr to last n charactors of newStr (n = target length)
   Set status to true

   IF subStr is different to target
      reset status to false
   ENDIF

   RETURN status

Next, let’s tap into the next big section related to the real-world implementation in JavaScript.

Code implementation

Let’s now translate our pseudocode to real code:

  1. We need to initialize a variable called newStr (we can enter any name we want) and set its value to our str parameter, but by deleting all available spaces.

We have several ways to do that. We can use a regular expression or split plus join() methods.

Using regex the code will look like this str.replace(/\s/g, ''). This code replaces all whitespace characters, \s, in str using ''.

If we want to use the second method, we’ll use:

  • str.split(' ') to create an array containing each word in str. Note that we use whitespace character ' ' as a separator.
  • str.split(' ').join('') to convert the array into a string that has no whitespace.

Let’s put all this in our real code:

function confirmEnding(str, target) {
  // with regex
  const newStr1 = str.replace(/\s/g, "")
  console.log(newStr1) // Iamatest

  // with split + join
  const strArr = str.split(" ")
  console.log(strArr) // ["I", "am", "a", "test"]
  const newStr2 = strArr.join("")
  console.log(newStr2) // Iamatest

  // in 1 line const newStr2 = str.split(' ').join('');
}

Delete all unnecessary spaces; the function will look like this:

function confirmEnding(str, target) {
  // with regex
  const newStr1 = str.replace(/\s/g, "")

  // with split + join
  const newStr2 = str.split(" ").join("")
}

In the next lines, we’ll stick to const newStr = str.split(' ').join('');.

  1. We set subStr to last n characters of newStr. We know that n = target length, so n = 2. The last 2 characters of newStr are st.

We can use the substring() method to get a substring from a string. It requires at least one parameter, which is the index of the first character to include in the returned substring.

To get that index, we can take the length of newStr to which we subtract the length of target. So, targetIndex = newStr.length - target.length. newStr.length = 8, target.length = 2. The new length will be targetIndex = 8 - 2 = 6.

Note: 6 of targetIndex is the 6th index, not the 6th character. The 6th index is the 7th character, s in our example (Iamatest).

Let’s put all this in our code:

function confirmEnding(str, target) {
  // previous code here...
  const strL = newStr.length
  const targetL = target.length
  const targetIdx = strL - targetL
  const subStr = newStr.substring(targetIdx)
  console.log(subStr) // st
}
  1. We set status to true.
let status = true
  1. We reset status to false.
if (subStr != target) {
   status = false
}
  1. We return status.
return status

Putting everything together, we have:

function confirmEnding(str, target) {
  const newStr = str.split(" ").join("")
  const strL = newStr.length
  const targetL = target.length
  const targetIdx = strL - targetL
  const subStr = newStr.substring(targetIdx)
  let status = true

  if (subStr != target) {
    status = false
  }

  return status
}

console.log(confirmEnding("I am a test", "st"))
Testing confirEnding()

Although the current code works fine, let’s try to improve the code to make it look more elegant.

function confirmEnding(str, target) {
  const newStr = str.split(" ").join("")
  const strL = newStr.length
  const targetL = target.length
  const targetIdx = strL - targetL
  const subStr = newStr.substring(targetIdx)

  return subStr == target
}

console.log(confirmEnding("I am a test", "st"))
Testing confirEnding()

We delete the status variable and return subStr == target. This also returns true if the two values are the same and false in other cases.

Next, we can try our implemented code with any of the cases given at the start or from our own.

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring