-2

I'm ought to do it without loops. with "if" and "else".

The user writes a random word in the text field at the html and the function needs to check if the first and last letters are equals.

If they are equal - the function will return the string without the first and the last characters. if the characters are not equal - the function will return the written string by the user.

unction firstLastletter(){

    let k = document.getElementsByClassName('text').value;
    let other = 'changed the string';
    



if(k.slice(0) == k.slice(-1)){

    return console.log(k);

}

else {
    return console.log(other);
}

}

i know that i miss a lot. but i have no clue how to implement the code in a right way.

many thanks..

Ido Vidal
  • 3
  • 2
  • You can use it as an array and compare first and last elements like `k[0] === k[k.length-1]` – Gavin Nov 18 '19 at 08:19
  • that's the thing... i am not allowed to solve it with array,push && pop. only using the if and else and the function. – Ido Vidal Nov 18 '19 at 08:40

1 Answers1

0

Something like this?

function firstlastletter(s) {
  var first = s.charAt(0);
  var last = s.charAt(s.length-1);
  if(first == last) return s.substring(1, s.length-1) 
  else return s;
}

https://jsfiddle.net/mte97hg1/19/

jared
  • 473
  • 3
  • 16
  • yes. that seems to be the more fit answer. i have questions though. why did you put in 'last' s.length-1 ? what does -1 do ? how does it target the last character? note it should return the string without the first and the last letters if they are the same characters. – Ido Vidal Nov 18 '19 at 08:52
  • `s.length-1` just gets me the string length minus one so that substring gets the string without the last character. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring – jared Nov 18 '19 at 09:04
  • here is what i wrote. i almost figured this out, but i need the function to return the string without the first and last characters if they are even. if they are not even it should return it as is. function firstLastLetter(){ let k = document.getElementById('text2').value; let str =k.slice(0,1); let str2 = k.slice(-1); if(str == str2){ k.replace(str,''); k.replace(str2,''); console.log(k); } else { return k; } } – Ido Vidal Nov 19 '19 at 17:21