Confirm the ending 123


#1
function confirmEnding(str, target) {
  //var arr=[];
  var arr=str.split(" ");//split the string intoarray
  //console.log(arr);
  var teststr=arr[arr.length-1];//taking last string of array as test string
  //console.log(teststr);
  var teststrarr=[];
  for(var i=teststr.length-1;i>=0;i--){//making array of test string and pushing it into test string array
    teststrarr.push(teststr[i]);
    //console.log(teststrarr)
  
    }
  var targetarr=target.split('').reverse();//making target string as array and reversing it to make comaprison 
  //console.log(targetarr);
  
  var teststrarr2=[];
  
 for(var j=0;j<=targetarr.length-1;j++){//comapring elements of both teststr array and targetarr and put the matched elements in new array teststrarr2
    if(teststrarr[j]===target[j]){
      teststrarr2.push(teststrarr[j]);
      console.log(teststrarr2);
    }
   if(teststrarr2.join('')===targetarr.join('')){//joining both arrays and comparing if compared it will be true otherwise false
     console.log(teststrarr2,targetarr);
     return true;
   }
  else{
  return false;
  }
  
}
}

confirmEnding("open sesame", "same");

hey guys in this program I am trying to confirm the ending of a string by comparing it with target string. The program should return true if target string is in the ending of test string otherwise false. My code is not returning true here. I have tried to print the result after ever logic and it seems like there is some problem when I am comparing the elements. Even this thing can be done by substr bultin method but I am trying to use this logic… Please help me identifying the problem Thanks


#2

if(teststrarr[j]===target[j])

i think you wanted to check with targetarr[j] not target[j]

and

you need to call the function with console.log() to print the returning value.

console.log(confirmEnding("open sesame", "same"));


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.