How to check if a string ends with a given string in JavaScript
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 returntrue.confirmEnding("Connor", "n")should returnfalse.confirmEnding("He has to give me a new name", "name")should returntrue.confirmEnding("Open sesam", "game")should returnfalse.confirmEnding("Abstraction", "action")should returntrue.
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:
- Delete all the spaces, so the string becomes
Iamatest. - The length of the target string is
2. - The last two characters are
st(ncharacters). - Comparison
st==st. - 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:
- We need to initialize a variable called
newStr(we can enter any name we want) and set its value to ourstrparameter, 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 instr. 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('');.
- We set
subStrto lastncharacters ofnewStr. We know thatn = target length, son = 2. The last 2 characters ofnewStrarest.
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
targetIndexis the 6th index, not the 6th character. The 6th index is the 7th character,sin 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
}
- We set
statustotrue.
let status = true
- We reset
statustofalse.
if (subStr != target) {
status = false
}
- We return
status.
return status
Putting everything together, we have:
function confirmEnding(str, target) {const newStr = str.split(" ").join("")const strL = newStr.lengthconst targetL = target.lengthconst targetIdx = strL - targetLconst subStr = newStr.substring(targetIdx)let status = trueif (subStr != target) {status = false}return status}console.log(confirmEnding("I am a test", "st"))
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.lengthconst targetL = target.lengthconst targetIdx = strL - targetLconst subStr = newStr.substring(targetIdx)return subStr == target}console.log(confirmEnding("I am a test", "st"))
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.
Free Resources
- undefined by undefined