글자를 늘리는 데 사용할 수있는 방법은 무엇입니까?
문자를 증가시키는 방법을 제공하는 Javascript 라이브러리 (예 : 밑줄, jQuery, MooTools 등)를 아는 사람이 있습니까?
다음과 같이 할 수 있기를 바랍니다.
"a"++; // would return "b"
간단하고 직접적인 솔루션
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
다른 사람들이 언급했듯이 단점은 문자 'z'와 같은 경우를 예상대로 처리하지 못할 수 있다는 것입니다. 그러나 그것은 당신이 그것을 원하는 것에 달려 있습니다. 위의 솔루션은 'z'뒤의 문자에 대해 '{'를 반환하고 이것은 ASCII에서 'z'뒤의 문자이므로 사용 사례에 따라 찾고있는 결과가 될 수 있습니다.
고유 한 문자열 생성기
(2019/05/09 업데이트)
이 답변은 많은 가시성을 받았기 때문에 Google에서이 문제에 걸림돌이되는 사람들을 잠재적으로 돕기 위해 원래 질문의 범위를 넘어 조금 확장하기로 결정했습니다.
내가 자주 원하는 것은 특정 문자 집합 (예 : 문자 만 사용)에서 순차적이고 고유 한 문자열을 생성하는 것이므로 여기에이를 수행 할 클래스를 포함하도록이 답변을 업데이트했습니다.
class StringIdGenerator {
constructor(chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
this._chars = chars;
this._nextId = [0];
}
next() {
const r = [];
for (const char of this._nextId) {
r.unshift(this._chars[char]);
}
this._increment();
return r.join('');
}
_increment() {
for (let i = 0; i < this._nextId.length; i++) {
const val = ++this._nextId[i];
if (val >= this._chars.length) {
this._nextId[i] = 0;
} else {
return;
}
}
this._nextId.push(0);
}
*[Symbol.iterator]() {
while (true) {
yield this.next();
}
}
}
용법:
const ids = new StringIdGenerator();
ids.next(); // 'a'
ids.next(); // 'b'
ids.next(); // 'c'
// ...
ids.next(); // 'z'
ids.next(); // 'A'
ids.next(); // 'B'
// ...
ids.next(); // 'Z'
ids.next(); // 'aa'
ids.next(); // 'ab'
ids.next(); // 'ac'
일반 자바 스크립트가 트릭을 수행해야합니다.
String.fromCharCode('A'.charCodeAt() + 1) // Returns B
주어진 문자가 z이면 어떨까요? 여기에 더 나은 해결책이 있습니다. A, B, C ... X, Y, Z, AA, AB, ... 등이됩니다. 기본적으로 Excel 스프레드 시트의 열 ID와 같은 문자를 증가시킵니다.
nextChar ( 'yz'); // "ZA"반환
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>
당신은 이것을 시도 할 수 있습니다
console.log( 'a'.charCodeAt(0))
먼저 Ascii 번호로 변환 .. 증분 .. 다음 Ascii에서 char로 변환 ..
var nex = 'a'.charCodeAt(0);
console.log(nex)
$('#btn1').on('click', function() {
var curr = String.fromCharCode(nex++)
console.log(curr)
});
FIDDLE 확인
일련의 문자를 여러 번 사용해야했기 때문에이 질문을 기반으로이 기능을 만들었습니다. 이것이 다른 사람들에게 도움이되기를 바랍니다.
function charLoop(from, to, callback)
{
var i = from.charCodeAt(0);
var to = to.charCodeAt(0);
for(;i<=to;i++) callback(String.fromCharCode(i));
}
- 부터- 시작 문자
- - 마지막 편지
- callback (letter)- 시퀀스의 각 문자에 대해 실행할 함수
사용 방법:
charLoop("A", "K", function(char) {
//char is one letter of the sequence
});
이 모든 답변에 추가 :
// first code on page
String.prototype.nextChar = function(i) {
var n = i | 1;
return String.fromCharCode(this.charCodeAt(0) + n);
}
String.prototype.prevChar = function(i) {
var n = i | 1;
return String.fromCharCode(this.charCodeAt(0) - n);
}
예 : http://jsfiddle.net/pitaj/3F5Qt/
가능한 한 가지 방법은 다음과 같습니다.
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 ...
이것은 잘 작동합니다.
var nextLetter = letter => {
let charCode = letter.charCodeAt(0);
let isCapital = letter == letter.toUpperCase();
if (isCapital == true) {
return String.fromCharCode((charCode - 64) % 26 + 65)
} else {
return String.fromCharCode((charCode - 96) % 26 + 97)
}
}
EXAMPLES
nextLetter("a"); // returns 'b'
nextLetter("z"); // returns 'a'
nextLetter("A"); // returns 'B'
nextLetter("Z"); // returns 'A'
웃음을위한 솔루션
function nextLetter(str) {
const Alphabet = [
// lower case alphabet
"a", "b", "c",
"d", "e", "f",
"g", "h", "i",
"j", "k", "l",
"m", "n", "o",
"p", "q", "r",
"s", "t", "u",
"v", "w", "x",
"y", "z",
// upper case alphabet
"A", "B", "C",
"D", "E", "F",
"G", "H", "I",
"J", "K", "L",
"M", "N", "O",
"P", "Q", "R",
"S", "T", "U",
"V", "W", "X",
"Y", "Z"
];
const LetterArray = str.split("").map(letter => {
if (Alphabet.includes(letter) === true) {
return Alphabet[Alphabet.indexOf(letter) + 1];
} else {
return " ";
}
});
const Assemble = () => LetterArray.join("").trim();
return Assemble();
}
console.log(nextLetter("hello*3"));
이것은 정말 오래되었습니다. 하지만이 기능이 필요했고 어떤 솔루션도 내 사용 사례에 최적이 아닙니다. a, b, c ... z, aa, ab ... zz, aaa ... 생성하고 싶었습니다. 이 간단한 재귀가 작업을 수행합니다.
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);
}
};
클로저에 {a : 'b', b : 'c', etc}를 사용하여 함수를 만듭니다.
let nextChar = (s => (
"abcdefghijklmopqrstuvwxyza".split('')
.reduce((a,b)=> (s[a]=b, b)), // make the lookup
c=> s[c] // the function returned
))({}); // parameter s, starts empty
용법:-
nextChar('a')
대문자 및 숫자 추가 :-
let nextCh = (
(alphabeta, s) => (
[alphabeta, alphabeta.toUpperCase(), "01234567890"]
.forEach(chars => chars.split('')
.reduce((a,b) => (s[a]=b, b))),
c=> s[c]
)
)("abcdefghijklmopqrstuvwxyza", {});
ps 일부 버전의 Javascript에서는 다음 [...chars]
대신 사용할 수 있습니다.chars.split('')
다음은 https://stackoverflow.com/a/28490254/881441에 제출 한 rot13 알고리즘의 변형입니다 .
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.
참고URL : https://stackoverflow.com/questions/12504042/what-is-a-method-that-can-be-used-to-increment-letters
'program tip' 카테고리의 다른 글
Rails는 데이터베이스에 대해 실행 된 마이그레이션을 어떻게 추적합니까? (0) | 2020.09.12 |
---|---|
UIButton에서 네이티브 "펄스 효과"애니메이션을 수행하는 방법-iOS (0) | 2020.09.11 |
JavaScript로 선택한 옵션 텍스트 가져 오기 (0) | 2020.09.11 |
자바 스크립트에서 정수 나누기를 수행하는 방법 (float이 아닌 int로 나누기 답변 얻기)? (0) | 2020.09.11 |
ArrayList에서 각 개체의 유형을 어떻게 알 수 있습니까? (0) | 2020.09.11 |