Randomize upper or lower case on all string characters

Some strange request, I know. But I have been looking for a solution to this for a long time. This is the effect I'm looking for:

var myString = "Hello I am randomly capitalized"

      

The result of the desired function:

hElLO i aM rAnDOmlY caPiTAlizED

      

I guess this is best done with javascript arrays anyway. Just looking for some creative ideas. Thank!

+3


source to share


2 answers


Here's one way

myString.split('').map(function(c){
    return c[Math.round(Math.random())?'toUpperCase':'toLowerCase']();
}).join('');

      

You can add this as a method prototype for a string object for ease of access:

String.prototype.toRandomCase = function() {
    return this.split('').map(function(c){
        return c[Math.round(Math.random())?'toUpperCase':'toLowerCase']();
    }).join('');
}

      

Then access to

console.log(myString.toRandomCase());

      




A little about how it works:

  • String.split

    used to split a string into an array of individual characters. Function used
  • Array.map

    ... This executes a callback function that is applied to each item in the array and returns a new resulting array with each value returned by the display function.
  • Inside the map function
    • Math.round(Math.random())

      used for randomness
    • The result of this is used with the ternary operator to get toLowerCase

      ortoUpperCase

      Math.Round(Math.random())?'toLowerCase':'toUpperCase'

    • The result of the ternary operator is used to access the corresponding property of the function by backtracking the character array and then calling. c[<ternary here>]()

  • Finally, it uses a method Array.join

    on the result of a function call map

    to concatenate the resulting array back into a string.

Code golf (efficiency)

RobG's answer has a more efficient approach than mine (please support his answer)

String.prototype.toRandomCase = function() {
    return this.toLowerCase().split('').map(function(c){
        return Math.random() < .5? c : c.toUpperCase();
    }).join('');
}

      

If anyone has any suggestions for improving this, please comment or edit this part of the answer

+7


source


Well, based on Joel's answer ...



myString.toLowerCase().split('').map(function(c){
    return Math.random() < .5? c : c.toUpperCase();
}).join('');

      

+4


source







All Articles