10

How do I choose a random letter from a-z and put it into a heading in my html by itself and make it replace any other letter that was there before? I don't know if what I've done works.

function randLetter( ) {

var letters =
    ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q"
    ,"r","s","t","u","v","w","x","y","z");

var letter = letters[Math.floor(Math.random()*letters.length)];

return letter

}

$('#letter').html('letter')
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
cparbr
  • 111
  • 1
  • 1
  • 4

3 Answers3

26

For Capital Letters you can use

String.fromCharCode(65+Math.floor(Math.random() * 26))

For Small letters

String.fromCharCode(97+Math.floor(Math.random() * 26))
4

Have this piece of code for your work

function randLetter() {
    var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
    var letter = letters[Math.floor(Math.random() * letters.length)];
    return letter
}

$('#letter').html(randLetter())

Fiddle

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

If you want to replace a random letter in the element that requires some more code. This will replace a random character with a random letter.

function randLetter() {
  var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
  var letter = letters[Math.floor(Math.random() * letters.length)];
  return letter;
}

var html = $('#letter').html();
var index = Math.floor(Math.random() * html.length);
var char = randLetter();

$('#letter').html(html.substr(0, index) + char + html.substr(index + char.length));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="letter">ABCDEFGHIJKLMNOPQRSTUVWXYZ</span>
Downgoat
  • 13,771
  • 5
  • 46
  • 69