Friday, July 3, 2009

Generate Random Number and Character JavaScript

function GenChar(mode, len) {
            var chars = null;
            var string_length = len;
            try {
                switch (mode) {
                    case 'U':
                        chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZ";
                        break;
                    case 'L':
                        chars = "abcdefghiklmnopqrstuvwxyz";
                        break;
                    case 'N':
                        chars = "0123456789";
                        break;
                    case 'UN':
                        chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
                        break;
                    case 'LN':
                        chars = "0123456789abcdefghiklmnopqrstuvwxyz";
                        break;
                    case 'Mix':
                        chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
                        break;
                    default: chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

                }
                var randomstring = '';
                for (var i = 0; i < string_length; i++) {
                    var rnum = Math.floor(Math.random() * chars.length);
                    randomstring += chars.substring(rnum, rnum + 1);
                }
            }
            catch (e) {
                document.write('An exception occurred.');
            }
            finally {
                return randomstring;
            }
        }

        function callGenfn(mode, func, length) {
            return func(mode, length);
        }
       

//callGenfn(Mode,FunctionName,length)

alert(callGenfn('N', GenChar,6));
alert(callGenfn('U', GenChar,6));
alert(callGenfn('L', GenChar,6));
alert(callGenfn('UN', GenChar,6));
alert(callGenfn('LN', GenChar,6));
alert(callGenfn('Mix', GenChar,6));

No comments: