-3

I'd like to reverse a word in a string with javascript, I wrote this code but it isn't working and I can't figure it out why. I want to write a word in a box and when I press the button has to appear the same word but reversed. For example, If I write "hello" in the textbox then it has to appear "olleh".

HTML:

<!DOCTYPE html> 
<html lang="it"> 
<head> 
<meta charset="utf-8"> 
<title>Reverse</title>
</head> 
<body> 
<input type="text" id="primo"><br>
<button type="button" onclick="rev()"> Reverse </button> 
<script type="text/javascript"> 
function rev(){
var string = document.getElementById("primo");
ciao = string.reverse();
document.write(ciao);
}
</script>
</body>
Gianni
  • 5
  • 5

1 Answers1

-1

String.prototype.reverse = function() {
  return this.split('').reverse().join('');
};

function rev() {
  var field = document.getElementById('primo');
  var ciao = field.value.reverse();
  document.body.insertAdjacentText('beforeend', ciao);
}
<input type="text" id="primo"><br>
<button type="button" onclick="rev()">Reverse</button> 
Wiktor Bednarz
  • 1,553
  • 10
  • 15