Bae

[Javascript] 문자열(대소문자 변환, 공백 제거, 문자열 검색, ...) 본문

Javascript

[Javascript] 문자열(대소문자 변환, 공백 제거, 문자열 검색, ...)

Bae:) 2022. 2. 9. 09:53

ㅁ 대소문자 변환

toUpperCase(): 모두 대문자로 변환

const str = 'my name is bae';
console.log(str.toUpperCase());	//'MY NAME IS BAE' 출력

 

toLowerCase(): 모두 소문자로 변환

const str = 'MY NAME IS BAE';
console.log(str.toLowerCase()); //'my name is bae' 출력

 

ㅁ 공백 제거

trim(): 문자열의 앞쪽과 뒤쪽의 공백을 제거

const str = '              hello          ';
console.log(str.trim());	//'hello' 출력

 

trimStart(): 문자열의 앞쪽 공백만 제거 = trimLeft(), trimEnd(): 문자열의 뒤쪽 공백만 제거 = trimRight()

const str = '           hello        ';
console.log(str.trimStart());	//'hello        ' 출력
console.log(str.trimEnd());		//'           hello' 출력

 

ㅁ 새로운 문자열 생성

repeat(): 문자열을 주어진 횟수만큼 반복해 이어붙인 새로운 문자열을 반환

const str = 'hi';
console.log(str.repeat(2));	//'hihi' 출력
console.log(str);			//'hi' 출력

 

padStart(): 문자열의 시작 위치부터, padEnd(): 문자열이 끝나는 부분부터 주어진 문자열을 추가해서 지정한 길이를 만족하는 새로운 문자열 반환

const str = 'hi';
console.log(str.padStart(5, 'v'));	//'vvvhi' 출력
console.log(str.padEnd(5, 'v'));	//'hivvv' 출력

 

ㅁ 문자열 검색

indexOf(): 주어진 키워드 값을 문자열에서 검색하여, 일치하는 첫 번째 인덱스를 반환, 일치하는 값을 찾이 못한 경우 -1을 봔환

const str = 'hello, my name is bae';
console.log(str.indexOf('hello'));	//0 출력
console.log(str.indexOf('hi'));		//-1 출력

 

includes(): 주어진 키워드 값을 문자열에서 검색하여, 일치하는 값이 있는 경우 true, 없는 경우 false를 반환

const str = 'hello, my name is bae';
console.log(str.includes('hello'));	//true 반환
console.log(str.includes('hi'));	//false 반환

 

startsWith(): 해당 문자열이 주어진 문자열로 시작하는지 여부를, endsWith(): 해당 문자열이 주어진 문자열로 끝나는지 여부를 true/false로 반환

const str = 'hello, my name is bae';
console.log(str.startsWith('hello'));	//true 반환
console.log(str.endsWith('hi'));		//false 반환
Comments