简体   繁体   English

如何在Javascript中生成数字字符串和字母?

[英]How can I generate a string of numbers and letters in Javascript?

I want to generate a line of numbers and letters in this format using Javascript. 我想使用Javascript以这种格式生成一行数字和字母。

Example: F35-HE4E-WAD-32S 例如: F35-HE4E-WAD-32S

So a line of 3-4-3-3 of random numbers and letters. 因此,一行3-4-3-3是随机数字和字母。

I would make a function which generates a random sequence matching a given template. 我将创建一个生成与给定模板匹配的随机序列的函数。 Something like this: 像这样:

function getSequence(template) {
    var r = '', ch, n;
    for (var i = 0; i < template.length; i++) {
        ch = template.substr(i, 1);
        if (ch == "d") {
            r += parseInt(Math.random() * 10);
        } else if (ch == "A") {
            r += String.fromCharCode(65 + parseInt(Math.random() * 26));
        } else if (ch == "w") {
            n = parseInt(Math.random() * 36);
            if (n > 9) {
                r += String.fromCharCode(55 + n);
            } else {
                r += n;
            }
        } else {
            r += ch;
        }
    }
    return r;
}
console.log(getSequence('Add-wwww-AAA-ddA'));

http://jsfiddle.net/xpt9od7c/ http://jsfiddle.net/xpt9od7c/

In the example given 'A' is used for capital letters, 'd' for digits (numbers) and 'w' for either. 在示例中,给定的字母“ A”代表大写字母,“ d”代表数字(数字),“ w”代表任一字母。 So 'Add-wwww' will return a sequence of one capital letter, two numbers, a hyphen, then four characters that can be either letters or numbers. 因此,“ Add-wwww”将返回一个序列,该序列由一个大写字母,两个数字,一个连字符和四个可以为字母或数字的字符组成。 You can then adapt according to what kind of sequence you need. 然后,您可以根据需要的顺序进行调整。

EDIT. 编辑。 Perhaps a cleaner and more reusable implementation is to make a function that converts a template character into a random character picked from the corresponding character set, then call Array.map to apply that function to each character of the template string. 也许更干净,更可重用的实现是创建一个将模板字符转换为从相应字符集中选取的随机字符的函数,然后调用Array.map将该函数应用于模板字符串的每个字符。

var CHAR_SETS = {
    d: '0123456789',
    A: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    w: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
};

function mapString(s, func) {
    return Array.prototype.map.call(s, func).join('')
}

function randChar(charType) {
    var chars = CHAR_SETS[charType];
    if (chars) {
        return chars.charAt(parseInt(Math.random() * chars.length));
    } else {
        return charType;
    }
}

console.log(mapString('Add-wwww-AAA-ddA', randChar));

http://jsfiddle.net/49hofey8/2/ http://jsfiddle.net/49hofey8/2/

Another option is to use replace : 另一种选择是使用replace

var CHAR_SETS = {
    d: '0123456789',
    A: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    w: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
};

function randChar(charType) {
    var chars = CHAR_SETS[charType];
    return chars.charAt(parseInt(Math.random() * chars.length));
}
console.log('Add-wwww-AAA-ddA'.replace(/[Adw]/g, randChar));

http://jsfiddle.net/so3pf271/1/ http://jsfiddle.net/so3pf271/1/

I would use something more generic.You can then reuse your functions for other code purposes. 我会使用更通用的东西,然后可以将函数重用于其他代码用途。

 Number.MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; Number.MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -Number.MAX_SAFE_INTEGER; Number.toInteger = Number.toInteger || function(inputArg) { var number = +inputArg, val = 0; if (number === number) { if (!number || number === Infinity || number === -Infinity) { val = number; } else { val = (number > 0 || -1) * Math.floor(Math.abs(number)); } } return val; }; function clampSafeInt(number) { return Math.min(Math.max(Number.toInteger(number), Number.MIN_SAFE_INTEGER), Number.MAX_SAFE_INTEGER); } Array.isArray = Array.isArray || function(inputArg) { return {}.toString.call(inputArg) === '[object Array]'; } function isString(inputArg) { return {}.toString.call(inputArg) === '[object String]'; } function generateChars(first, last) { first = isString(first) && first.length ? first.charCodeAt(0) : 0; last = isString(last) && last.length ? last.charCodeAt(0) : 0; var chars = [], index; for (index = first; index <= last; index += 1) { chars.push(String.fromCharCode(index)); } return chars; } function randomInt(min, max) { var tmp, val; if (arguments.length === 1) { max = min; min = 0; } min = clampSafeInt(min); max = clampSafeInt(max); if (min > max) { tmp = min; min = max; max = tmp; } tmp = max - min + 1; if (tmp > Number.MAX_SAFE_INTEGER) { throw new RangeError('Difference of max and min is greater than Number.MAX_SAFE_INTEGER: ' + tmp); } else { val = Math.floor(Math.random() * tmp) + min; } return val; } function stringFromPool(ary, howMany) { var str = ''; if (Array.isArray(ary)) { for (index = 0, howMany = Number.toInteger(howMany); index < howMany; index += 1) { str += ary[randomInt(ary.length - 1)]; } } return str; } var getSequence = (function() { var lower = generateChars('a', 'z'), upper = generateChars('A', 'Z'), digit = generateChars('0', '9'), lowerDigit = lower.concat(digit), upperDigit = upper.concat(digit), all = lower.concat(upper, digit); return function(template) { var str = '', index, length, chr; if (isString(template) && template.length) { for (index = 0, length = template.length; index < length; index += 1) { chr = template.charAt(index); switch (chr) { case 'a': str += stringFromPool(lower, 1); break; case 'A': str += stringFromPool(upper, 1); break; case 'd': str += stringFromPool(digit, 1); break; case 'c': str += stringFromPool(lowerDigit, 1); break; case 'C': str += stringFromPool(upperDigit, 1); break; case 'x': str += stringFromPool(all, 1); break; default: str += chr; } } } return str; }; }()); function generatePattern() { return getSequence('CCC-CCCC-CCC-CCC'); } function runMaxTimes(fn, howMany) { howMany = Number.toInteger(howMany); var count = 0; return function() { if (count < howMany) { count += 1; return fn.apply(this, arguments); } }; } document.getElementById('generate').addEventListener('click', runMaxTimes(function(e) { this.textContent += generatePattern() + '\\n'; }, 5).bind(document.getElementById('out')), false); 
 <button id="generate">Generate</button> <pre id="out"></pre> 

A VERY simple way to do it would be to create an string of all of the characters that you want to include (digits and uppercase letters, in your case) and then use random number generation to pick which character to add from that string. 一种非常简单的方法是创建一个包含所有要包括的字符的字符串(在您的情况下为数字和大写字母),然后使用随机数生成从该字符串中选择要添加的字符。 You would then repeat this process with a loop . 然后,您将使用循环重复此过程。 . . inserting dashes, where appropriate . 在适当的地方插入破折号。 . . until you had built out the string. 直到建立了字符串为止。

Something like this: 像这样:

var sValidCharacters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sCharCode = "";

for (i = 0; i < 13; i++) {
    sCharCode = sCharCode + sValidCharacters.charAt(parseInt(Math.random() * sValidCharacters.length));

    if ((i === 2) || (i === 6) || (i === 9)) {
        sCharCode = sCharCode + "-";
    }
}

console.log(sCharCode);

The nice thing about this approach is that, since it uses the length of sValidCharacters when determining the random number, you can add or subtract valid characters from that "source string", without changing any of the code. 这种方法的优点在于,由于在确定随机数时会使用sValidCharacters的长度, sValidCharacters您可以在“源字符串”中添加或减去有效字符,而无需更改任何代码。

Some sample outputs from a few test runs: 一些测试运行的一些示例输出:

HF1-EH46-RKP-8OL
VJ6-TRE1-DVA-WR7
156-ODA4-350-TP5
XBA-Q599-KZJ-FST
N82-DNM8-QSS-GUK

EDIT: 编辑:

I took a second pass to make it a little more flexible, so that all you need to do is change parameters to generate the code of your choice. 我经过了第二步,使其更具灵活性,因此您所需要做的就是更改参数以生成您选择的代码。 Here is the new "functionized" version: 这是新的“功能化”版本:

function generateCode(sSourceCharacters, iCodeLength, sSeperator, aSeparatorPositions) {
    var sNewCode = "";

    for (i = 0; i < iCodeLength; i++) {
        sNewCode = sNewCode + sSourceCharacters.charAt(parseInt(Math.random() * sSourceCharacters.length));

        if (aSeparatorPositions.indexOf(i + 1) !== -1) {
            sNewCode = sNewCode + sSeperator;
        }
    }

    return sNewCode;
}

This way, you can pass in any parameters that you want, to generate a code, based on what you need. 这样,您可以传入所需的任何参数,以根据需要生成代码。 For your specific question, the options would be passed like this: 对于您的特定问题,将通过以下方式传递选项:

var charGroup = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var length = 13;
var divider = "-";
var dividerLocations = [3, 7, 10]; // the numbers indicate which character to place the divider after

var generatedCode = generateCode(charGroup, length, divider, dividerLocations);

But, you could also pass in something like: 但是,您也可以传递类似以下内容的内容:

var charGroup = "0123456789";
var length = 11;
var divider = ".";
var dividerLocations = [3, 6, 9];

. . . to get randomly generated IP addresses (though, in no way guaranteed to be valid :D ): Examples: 获取随机生成的IP地址(尽管绝不保证其有效:D):示例:

235.232.608.74
125.227.649.68
983.678.369.71
605.708.890.97
537.554.201.23

Or this, to generate a random, 4-letter, "encoded" swear word: :D 或这样,生成一个随机的,四字母的“编码”脏话:D

var charGroup = "!@#$%^&*()?";
var length = 4;
var divider = "";
var dividerLocations = [];

Results: 结果:

@%$%
)?$&
*&(!
!^@)
*))#

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Javascript将13位数字缩短(编码)为短串的数字,字母和标点符号? - How can I shorten (encode) a thirteen-digit number to a short string of numbers, letters, and punctuation using Javascript? JavaScript:如何从字符串中删除所有包含(或紧随其前)大写字母,数字或逗号的单词? - JavaScript: How can I remove any words containing (or directly preceding) capital letters, numbers, or commas, from a string? Javascript RegExp生成包含4个小写字母,4个大写字母和4个数字的字符串 - Javascript RegExp Generate string with 4 lower case letters, 4 upper case letters & 4 numbers 如何在 javascript 中生成一个波动为 1 的随机数数组? - How can I generate an array of random numbers that fluctuate by 1 in javascript? 如何在有条件的JavaScript中生成随机数字序列? - How can I generate a random sequence of numbers in JavaScript with conditions? 如果字符串包含数字和字母,我如何按字母顺序对字符串进行排序? - How can I sort a string alphabetically if the string contains both numbers and letters? 在Javascript中,如何检查字符串是否只是字母+数字(允许下划线)? - In Javascript, how do I check if string is only letters+numbers (underscore allowed)? Javascript-如何检查正则表达式以确保字符串至少包含一个字母/数字序列? - Javascript - how do I check regex to ensure a string contains at least one sequence of letters/numbers? 如何替换JavaScript字符串中除字母和数字之外的所有内容(空格/符号)? - How do I replace everything(whitespaces/symbols) except letters and numbers in a JavaScript String? 正则表达式JavaScript-如何检查字符串是否全是字母,然后是所有数字 - Regex JavaScript - how to check if a string is all letters and then all numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM