Randomly get a character from a string using JavaScript?

coderguy asked this question 7 months ago
coderguy on Dec 23, 2021

I have a string like this:

"my example string"

How can I grab a character from that string at random?

I'm using JavaScript?

4 suggested answers
1 reply
looper003 on Jan 4
var myString = "fkasjdfjasodfiasdf"

var randomCharacter = myString[Math.floor(Math.random() * myString.length)]

This uses Math.random() to get a random character from the string at a random index position.

0 replies
suparman21 on Jan 4
function getRandomChar(string) {
  // remove any leading or trailing spaces
  string = string.trim()

  // remove any spaces inside the string
  string = string.replace(/\s/g, "") 

  // use Math.floor() to get the random character at a random index position
  return string[Math.floor(Math.random() * string.length)]

This function removes any spaces in the string before getting the random character. This will ensure it doesn't return an empty value.

1 reply
coderguy on Jan 4


softwareguy411 on Jan 4
string.charAt(Math.floor(Math.random() * string.length))
0 replies
yaboy01 on Jan 4

You can create a string.selectRandomChar() method on the string:

String.prototype.selectRandomChar = function() {
  return this[Math.floor(Math.random() * this.length)]

You can use it like this:

myString.selectRandomChar() // returns a random character from the given string
0 replies