如何增加字符串" A"得到" B"在Javascript?
function incrementChar(c)
{
}
答案 0 :(得分:9)
你可以尝试
var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'
所以,在一个函数中:
function incrementChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1)
}
请注意,这是ASCII order,例如'Z' -> '['
。如果你想让Z回到A,尝试一些稍微复杂的东西:
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
var index = alphabet.indexOf(c)
if (index == -1) return -1 // or whatever error value you want
return alphabet[index + 1 % alphabet.length]
}
答案 1 :(得分:1)
var incrementString = function(string, count){
var newString = [];
for(var i = 0; i < string.length; i++){
newString[i] = String.fromCharCode(string[i].charCodeAt() + count);
}
newString = newString.join('');
console.log(newString);
return newString;
}
如果您有循环通过
,此功能也可以帮助您