4 ways to check a string ending in Javascript
from the Basic Algorithm Scripts in JavaScript list
In this article, we will discuss about possible solutions to Freecodecamp “Confirm Ending” problem which is available in the “JavaScript Algorithms and Data Structures” curriculum.
Problem : Check if a string ends with a given target string in Javascript.
1- Solution using endsWith() method
Of course, there is a one-line solution to the problem using .endsWith method. Using it, the solution should be like the one below :
I use the Conditional (ternary) operator to ease understanding. The code returns a boolean whether str ends with target or not.
But as mentioned in the original problem statement, we must not use the endsWith method to resolve it.
Let’s then go through all other possible solutions that I found out.
2- Solution using slice() method
What this actually does is :
- First getting the length of the target string “target” ;
- Extracting a substring using the slice method from the main given string “str”. The parameter in slice’s brackets indicates the starting position from where the extracted string is got ;
- Finally checking if the extracted string is equals to the target string.
If all these are in order then it returns true otherwise false as result.
3- Solution using substring() method
This solution is practically the same as the previous. Because substring and slice methods are both used to extract strings.
4- Solution using RegExp()
Regular expressions are patterns used to match character combinations in strings. RegExp() is the constructor function used to create them.
Let me break it down to ease understanding !
let myRegex = RegExp(`${target}$`,'g');
This first line of code means that we are creating a new regex. RegExp takes as first parameter the pattern. The first dollar sign$
and the curly brackets{}
help accept target
as a variable inside the pattern. The second dollar sign$
indicates that target
variable should be looked up at the end of the string.
let ret = myRegex.test(str);
The test() method is useful to check if a string contains a regex or not. It returns true if it does otherwise false.
These are my solutions to the problem. I Really appreciate yours in comments.
You can check out my Basic Algorithm Scripts in JavaScript list.