Does anyone know of a Javascript library (e.g. underscore, jQuery, MooTools, etc.) that offers a method of incrementing a letter?
I would like to be able to do somet
I needed to use sequences of letters multiple times and so I made this function based on this SO question. I hope this can help others.
function charLoop(from, to, callback)
{
var i = from.charCodeAt(0);
var to = to.charCodeAt(0);
for(;i<=to;i++) callback(String.fromCharCode(i));
}
How to use it:
charLoop("A", "K", function(char) {
//char is one letter of the sequence
});
See this working demo
Here is a variation of the rot13 algorithm I submitted on https://stackoverflow.com/a/28490254/881441:
function rot1(s) {
return s.replace(/[A-Z]/gi, c =>
"BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza"[
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(c) ] )
}
The input code in the bottom and the looked up codec is on the top (i.e. the output code is the same as the input code but shifted by 1). The function only changes letters, i.e. if any other character is passed in, it will be unchanged by this codec.
You can try this
console.log( 'a'.charCodeAt(0))
First convert it to Ascii number .. Increment it .. then convert from Ascii to char..
var nex = 'a'.charCodeAt(0);
console.log(nex)
$('#btn1').on('click', function() {
var curr = String.fromCharCode(nex++)
console.log(curr)
});
Check FIDDLE
This is really old. But I needed this functionality and none of the solutions are optimal for my use case. I wanted to generate a, b, c...z, aa,ab...zz, aaa... . This simple recursion does the job.
function nextChar(str) {
if (str.length == 0) {
return 'a';
}
var charA = str.split('');
if (charA[charA.length - 1] === 'z') {
return nextID(str.substring(0, charA.length - 1)) + 'a';
} else {
return str.substring(0, charA.length - 1) +
String.fromCharCode(charA[charA.length - 1].charCodeAt(0) + 1);
}
};
Plain javascript should do the trick:
String.fromCharCode('A'.charCodeAt() + 1) // Returns B
One possible way could be as defined below
function incrementString(value) {
let carry = 1;
let res = '';
for (let i = value.length - 1; i >= 0; i--) {
let char = value.toUpperCase().charCodeAt(i);
char += carry;
if (char > 90) {
char = 65;
carry = 1;
} else {
carry = 0;
}
res = String.fromCharCode(char) + res;
if (!carry) {
res = value.substring(0, i) + res;
break;
}
}
if (carry) {
res = 'A' + res;
}
return res;
}
console.info(incrementString('AAA')); // will print AAB
console.info(incrementString('AZA')); // will print AZB
console.info(incrementString('AZ')); // will print BA
console.info(incrementString('AZZ')); // will print BAA
console.info(incrementString('ABZZ')); // will print ACAA
console.info(incrementString('BA')); // will print BB
console.info(incrementString('BAB')); // will print BAC
// ... and so on ...