Hi,
I’ve been working on “Confirming the Ending” challenge in basic algorithm scripting section.
I was able to write it on my own and achieved the desired result. In the challenge, it was given to use ‘String.prototype.substr()’ as helpful links. But I did not use it and I was able to achieve the final output with what I’ve learned so far. I haven’t come across substrings as far as I remember.
So, I’d like to know your comments and improvements to the code.
Thanks for any help.
Here is my code:
>> function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
var splitStr=str.split(" ");
//return splitStr.length;
if(splitStr.length>1){
var lastWord=splitStr[splitStr.length-1];
im rather new as well…i can show you what i did. i guess javascript is cool because our ways look different but both work.
function confirmEnding(str, target) {
let a = target.length;
let b = str.length;
let c = str.slice(b-a);
if(c===target){return true;}
else{return false;}
wow… thanks, Benjaminadk. It indeed shrinked to two lines. I should practice a lot not to use if/else statements all the time.
I hope you did not use the word ‘let’ in your code. But the slice takes two arguments, isn’t it? You’ve written slice(b-a)?
@owel - thank you. still learning all the concepts of string manipulations. I hope one day I will write light weight code like you guys.
yah slice can take one or two arguments. b-a is actually one argument though. js will do that math first then do slice. just like math parenthesis first. slice(a,b) would be start at a and end at b and whats in between gets returned
I went down a different (maybe slightly cheaty) route. Regex seemed like a better fit for checking a string ending. But adding a variable to regex was a struggle till I saw this on Stack Overflow.
ble-inside-a-regular-expression
So my solution using this method was…
function confirmEnding(str, target) {
let stringCheck = new RegExp(target + '$', "i");
return stringCheck.test(str);
}