📌 텍스트 대 소문자 변경
📍 텍스트 전체 대문자
- toUpperCase() 메서드를 사용하여 문자열 전체를 대문자로 변경
// toUpperCase - 대문자
const text = 'tistory blog';
console.log(text.toUpperCase()); // TISTORY BLOG
📍텍스트 전체 소문자
- toLowerCase() 메서드를 사용하여 문자열 전체를 소문자로 변경
// toLowerCase - 소문자
const text = 'TISTORY BLOG';
console.log(text.toLowerCase()); // tistory blog
📍 텍스트 첫글자만 대문자
const text = 'tistory blog';
console.log(text.charAt(0)) // t
console.log(text.charAt(0).toUpperCase()) // T
console.log(text.slice(1)) // istory blog
// ✅
const firstText = text.charAt(0).toUpperCase() + text.slice(1);
console.log(firstText) // Tistory blog
※ charAt(i) 메서드: index에 위치한 문자 반환, 0부터 시작 없는 경우 빈문자 반환
※ slice(start, end) : 시작(0)과 끝(1)(0글자만 반환), 시작만 입력한 경우 시작부터 끝까지
📍 텍스트 첫글자만 소문자
const text = 'TISTORY BLOG';
const firstText = text.charAt(0).toLowerCase() + text.slice(1);
console.log(firstText) // tISTORY BLOG
📍첫글자 대문자 소문자 구분
const text = 'Tistory blog';
const firstText = text.charAt(0);
if(firstText === firstText.toUpperCase()){
console.log('대문자')
}else if(firstText === firstText.toLowerCase()){
console.log('소문자')
}
// 첫 글자와 toUpperCase, toLowerCase 메서드를 사용한 후 비교
반응형
📍 띄어쓰기 기준 첫글자만 대소문자로 변경
function formatText (text, capital=true) {
const textSplit = text.split(' '); // 띄어쓰기 기준
console.log(textSplit); // ['tistory', 'blog']
const result = textSplit.map(textItem => (
capital
? textItem.charAt(0).toUpperCase() + textItem.slice(1)
: textItem.charAt(0).toLowerCase() + textItem.slice(1)
))
console.log(result); // ['Tistory', 'Blog']
console.log(result.join(' ')) // ' ' 띄어쓰기로 연결
}
const text = 'tistory blog';
console.log(formatText('tistory blog')); // Tistory Blog
console.log(formatText('Tistory Blog', false)); // tistory blog
console.log(formatText('TISTORY BLOG', false)); // tISTORY bLOG
🔽 🔽 🔽
function formatText (text, capital=true) {
return text.split(' ')
.map(textItem =>
capital
? textItem.charAt(0).toUpperCase() + textItem.slice(1)
: textItem.charAt(0).toLowerCase() + textItem.slice(1)
)
.join(' ');
}
※ join(구분자) 메서드 : 배열 요소 결합하여 하나의 문자열로 만들며, 구분자를 통해 배열 사이 사이 연결하여 문자열로 만든다.
✍️ 기록
감사합니다. 😁
반응형
'✍️ 기록 > Javascript' 카테고리의 다른 글
[highlight.js] 구문 강조, 번호 추가, navigator.clipboard 복사 (0) | 2025.05.07 |
---|---|
[JavaScript] moment.js로 쉽게 날짜, 시간 사용 및 기간 설정 (2) | 2025.04.10 |
[JavaScript] forEach, map, flatMap, filter, find, findIndex, reduce, reduceRight, some, every 배열 메서드 (1) | 2025.03.26 |
[JavaScript] for, for...in, for...of, while, do...while, 반복문 (1) | 2025.03.26 |
[JavaScript] 변수(Variable), 스코프(Scope), 식별자(Identifier) (0) | 2019.09.24 |
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.