>  기사  >  웹 프론트엔드  >  알파벳 색인을 기준으로 문자열의 문자를 반복합니다.

알파벳 색인을 기준으로 문자열의 문자를 반복합니다.

Susan Sarandon
Susan Sarandon원래의
2024-10-18 14:57:02431검색

Repeat the Character in a string based on its Alphabetical index

문자열을 가져와 표시하는 반복알파 함수 작성
각 알파벳 문자를 알파벳 색인만큼 반복합니다.

해결책

const range = (start, stop, step) =>
  Array.from(
    { length: Math.ceil((stop - start) / step) },
    (_, i) => start + i * step
  );

const upperAlpha = range("A".charCodeAt(0), "Z".charCodeAt(0) + 1, 1).map((x) =>
  String.fromCharCode(x)
);

const lowerAlpha = range("a".charCodeAt(0), "z".charCodeAt(0) + 1, 1).map((x) =>
  String.fromCharCode(x)
);

function getAlphaIndex(char) {
  if (char === char.toUpperCase()) {
    return upperAlpha.indexOf(char) + 1;
  }

  if (char === char.toLowerCase()) {
    return lowerAlpha.indexOf(char) + 1;
  }
}

function repeatAlpha(text) {
  let occurrence = [];

  Array.from(text).forEach((char) => {
    let count = getAlphaIndex(char);
    let result = Array(count).fill(char).join("");
    occurrence.push(result);
  });

  return occurrence.join("");
}

console.log(repeatAlpha("Becky"));
console.log(repeatAlpha("neNgi"));
console.log(repeatAlpha("ChInwendu"));
console.log(repeatAlpha("dindustack"));

결과

BBeeeeeccckkkkkkkkkkkyyyyyyyyyyyyyyyyyyyyyyyyy
nnnnnnnnnnnnnneeeeeNNNNNNNNNNNNNNgggggggiiiiiiiii
CCChhhhhhhhIIIIIIIIInnnnnnnnnnnnnnwwwwwwwwwwwwwwwwwwwwwwweeeeennnnnnnnnnnnnndddduuuuuuuuuuuuuuuuuuuuu
ddddiiiiiiiiinnnnnnnnnnnnnndddduuuuuuuuuuuuuuuuuuuuusssssssssssssssssssttttttttttttttttttttaccckkkkkkkkkkk

위 내용은 알파벳 색인을 기준으로 문자열의 문자를 반복합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.