알파벳 증가
기본 : 아스키 코드를 이용하여 증가시킴
- charCodeAt : 문자열을 아스키 코드로 변환
- fromCharCode : 아스키코드를 문자열을 구성
https://stackoverflow.com/questions/12504042/what-is-a-method-that-can-be-used-to-increment-letters
String.fromCharCode('A'.charCodeAt() + 1) // Returns B
function nextChar(c) {
var u = c.toUpperCase();
if (same(u,'Z')){
var txt = '';
var i = u.length;
while (i--) {
txt += 'A';
}
return (txt+'A');
} else {
var p = "";
var q = "";
if(u.length > 1){
p = u.substring(0, u.length - 1);
q = String.fromCharCode(p.slice(-1).charCodeAt(0));
}
var l = u.slice(-1).charCodeAt(0);
var z = nextLetter(l);
if(z==='A'){
return p.slice(0,-1) + nextLetter(q.slice(-1).charCodeAt(0)) + z;
} else {
return p + z;
}
}
}
function nextLetter(l){
if(l<90){
return String.fromCharCode(l + 1);
}
else{
return 'A';
}
}
function same(str,char){
var i = str.length;
while (i--) {
if (str[i]!==char){
return false;
}
}
return true;
}
// below is simply for the html sample interface and is unrelated to the javascript solution
var btn = document.getElementById('btn');
var entry = document.getElementById('entry');
var node = document.createElement("div");
node.id = "node";
btn.addEventListener("click", function(){
node.innerHTML = '';
var textnode = document.createTextNode(nextChar(entry.value));
node.appendChild(textnode);
document.body.appendChild(node);
});
<input id="entry" type="text"></input>
<button id="btn">enter</button>
--
function nextChar(c) {
var u = c.toUpperCase();
if (same(u,'Z')){
var txt = '';
var i = u.length;
while (i--) {
txt += 'A';
}
return (txt+'A');
} else {
var p = "";
var q = "";
if(u.length > 1){
p = u.substring(0, u.length - 1);
q = String.fromCharCode(p.slice(-1).charCodeAt(0));
}
var l = u.slice(-1).charCodeAt(0);
var z = nextLetter(l);
if(z==='A'){
return p.slice(0,-1) + nextLetter(q.slice(-1).charCodeAt(0)) + z;
} else {
return p + z;
}
}
}
function nextLetter(l){
if(l<90){
return String.fromCharCode(l + 1);
}
else{
return 'A';
}
}
function same(str,char){
var i = str.length;
while (i--) {
if (str[i]!==char){
return false;
}
}
return true;
}
'기타 > Javascript' 카테고리의 다른 글
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (0) | 2018.07.05 |
---|---|
NPM (0) | 2018.06.19 |
Modules (0) | 2018.05.29 |
Enhanced Object Literals (0) | 2018.05.29 |
ArrowFunction (0) | 2018.05.29 |