✍️ 기록/Javascript
[JavaScript] 전체 글자, 첫글자 대소문자 변경
김물사
2025. 4. 2. 11:13
📌 텍스트 대 소문자 변경
📍 텍스트 전체 대문자
- 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(구분자) 메서드 : 배열 요소 결합하여 하나의 문자열로 만들며, 구분자를 통해 배열 사이 사이 연결하여 문자열로 만든다.
✍️ 기록
감사합니다. 😁
반응형