
코딩테스트를 준비하면서 알아두면 좋을 JS 메소드들을 정리해본다.
다양한 메소드들을 이해하고 사용할 줄 알면, 효율적인 코드 작성이 가능해지기에 익혀둬야 한다.
start 번째 index부터, end 번째 index전 까지 추출한다. let name = 'LeeApplean';
let arr = name.slice(3,8);
console.log(arr); // 'Apple' -> 3번째 배열부터 8번째 배열전 까지 추출하여 반환
console.log(name); //'LeeApplean';
let name = 'LeeApplean';
let arr = name.slice(-2);
console.log(arr); // 'an'
toUpperCase(): 문자 및 문자열을 대문자로 변경toLowerCase(): 문자 및 문자열을 소문자로 변경const name = 'Lee Yun Hwan';
console.log(name.toUpperCase()); // 'LEE YUN HWAN';
console.log(name.toLowerCase()); // 'lee yun hwan';
console.log(name[0].toLowerCase()); // 'l'
const str1 = 'pop corn corn';
console.log(str1.replace('corn', 'state')); // 'pop state corn'
/string/g : string에 해당하는 모든 문자열을 교체할 수 있다.const str2 = 'ice cream yous cream';
console.log(str2.replace(/cream/g, 'Box')); // 'ice Box yous Box'
/string/gi : 대/소문자 상관없이 모든 문자열 교체const str3 = 'you You you you magnetic ';
console.log(str3.replace(/you/gi, 'super')); // 'super super super super magnetic'
const str = 'Lee Yun Hwan unanakadev';
// 공백을 기준으로 구분
console.log(str.split(' ')); // [Lee, Yun, Hwan, unanakadev]
// 공백을 기준으로 2개까지
console.log(str.split(' ', 2)); // [Lee, Yun]
// 문자로 모두 분리 (공백 포함)
console.log(str.split('')); // ['L', 'e', 'e', ,' ', 'Y', ... , 'a', 'n']
// 인수를 생략 시, 전체 문자열을 단일 요소로 하는 배열 반환
console.log(str.split()); // ['Lee Yun Hwan']
문자열.split('')의 경우, [...문자열]와 같이 스프레드 연산자 형태로 표현할 수 있다.console.log([...str]); // ['L', 'e', 'e', ,' ', 'Y', ... , 'a', 'n']
num만큼 반복한다. (문자열 곱하기)const str = 'hello';
console.log(str.repeat(3)); // 'hellohellohello'
[...arr])를 사용하여 원본 훼손을 막을 수도 있다.const arr = ['lee', 'yun', 'hwan']; // index: [0] [1] [2]
arr.splice(0,1,'kim');
console.log(arr); // ['kim','yun','hwan']
//join()을 사용하여 문자열로 변경할 수 있다.
console.log(arr.join(''));