JQuery — автоинкремент буквенно-цифровой PHP, JavaScript

Я хочу сделать автоинкремент буквенно-цифровой, и это только для вывода

если я нажимаю кнопку, есть выход AA001, а затем я снова нажимаю кнопку, есть выход AA002

-1

Решение

Здесь не используются «умные» приемы, но они короче, их легче понять и настроить. Он также использует числа, чтобы не увеличивать длину строки так быстро. Он увеличивается от 0 до 9, затем a-z, но предполагается, что для начала вы должны ввести ‘a’. Вывод всегда начинается с символа алфавита, если ваш ввод также начинается с символа алфавита, поэтому его можно использовать как имена переменных PHP

var nextVarName = function(str) {
// Position of char to change.
var change = str.length - 1;
// The value of that char.
var change_char = str[change];
// Number of zeros to append when flipping.
var zeros = 0;
// Iterate backwards while there's a z (flipping).
while (change_char == 'z') {
// Increase the length of appended zeros
zeros++;
// Move the char to change back.
change_char = str[--change];
}
if (change_char == undefined) {
// Full flip - string increases in length.
str = 'a' + Array(str.length + 1).join("0");
} else {
// Normal increment with partial flip and 9->a handling.
str = str.substr(0, change)
+ (change_char == '9' ? 'a' : String.fromCharCode(str.charCodeAt(change) + 1))
+ Array(zeros + 1).join('0');
}
return str;
};

var vname = 'a';
for (var i = 0; i < 5; i++) {
vname = nextVarName(vname);
console.log(vname);
}

Результаты будут следующими:

z —> a0

9z —> a0 (неожиданный ввод)

ab1zde —> ab1zdf

abcdzz —> abce00

zzzzz —> a00000

abcyzz —> abcz00

9000 —> 9001 (неожиданный ввод)

https://jsfiddle.net/e20kfvky/

График того, сколько переменных (которые начинаются с буквы алфавита) создаются для каждой длины, выглядит следующим образом:

1: 26, 2: 936, 3: 33696, 4: 1213056 … n: 36 ^ n - 10 * 36 ^ (n - 1)

1

Другие решения

Следующий код сгенерирует токен, который вы можете продвинуть одним. Он использует несколько небольших классов, чтобы сделать его модульным. Функция, которую вы прикрепляете к кнопке, вызывает функцию, следующую за токеном, как показано в самом низу.

//Element in a big token
function Increment(startval, endval) {
this.start = startval.charCodeAt(0);
this.cur = this.start;
this.end = endval.charCodeAt(0);

//Returns the current value
this.get = function() {
if (this.cur <= this.end) {
return String.fromCharCode(this.cur);
} else {
return null;
}
}

//Advances the value we will show
this.next = function() {
this.cur += 1;
return this.get();
}

//Reset it to the beginning
this.reset = function() {
this.cur = this.start;
}
}

function Token() {
this.token = [
new Increment("A", "Z"),
new Increment("A", "Z"),
new Increment("0", "9"),
new Increment("0", "9"),
new Increment("0", "9")
];
this.get = function() {
return this.token.map(function(cur) {
return cur.get();
}).join("");
}
this.next = function() {
//From the back to the front
for (var i = this.token.length - 1; i >= 0; i--) {
if (this.token[i].next() == null) {
//If we exhausted all possible values, continue
this.token[i].reset();
} else {
//Until we advance one that has still values left
break;
}
}
return this.get();
}
}

//Now we are just showing off...
var a = new Token();
for (var i = 0; i < 15; i++) {
console.log(a.next());
}
0

const getNextAlphaString = function (str) {
"use strict";
str=str.toUpperCase();
let chars;
chars = str.split("");
const strLen = str.length;
let continueIncermenting = true;
for (let i = strLen - 1; i >= 0; i = i - 1) {
let asciiVal;
asciiVal = chars[i].charCodeAt(0);
if (isNaN(asciiVal)) {
return str;
}


if (continueIncermenting === true) {
if (asciiVal >= 48 && asciiVal < 57) {
chars[i] = String.fromCharCode(asciiVal + 1);
continueIncermenting = false;
break;
} else if (asciiVal == 57) {
chars[i] = '0';
continueIncermenting = true;
}
if (asciiVal >= 65 && asciiVal < 90) {
chars[i] = String.fromCharCode(asciiVal + 1);
continueIncermenting = false;
break;
} else if (asciiVal == 90) {
chars[i] = String.fromCharCode(65);

continueIncermenting = true;
}
} else {
if (asciiVal == 90) {
continueIncermenting = true;
chars[i] = String.fromCharCode(65);
}
if (asciiVal == 57) {
continueIncermenting = true;
chars[i] = '0';
}
}
}
if (continueIncermenting === true) {
let firstAcii = chars[0].charCodeAt(0);
if (isNaN(firstAcii)) {
return str;
}
if ((firstAcii >= 65 && firstAcii <= 90) || (firstAcii >= 97 && firstAcii <= 122)) {
return 'A' + chars.join('').toUpperCase();
}
if (firstAcii >= 48 && firstAcii <= 57) {
return '0' + chars.join('').toUpperCase();
}
}
return chars.join('').toUpperCase();

};

Результаты будут следующими:

ab1zde —> AB1ZDF

abcdzz —> ABCEAA

zzzzz —> АААААА

abcyzz —> ABCZAA

9000 —> 9001

0