참고 학습자료
String을 다루기 위한 다양한 메서드들을 다뤄볼까 합니다. 이러한 메서드들은 구현력이 매우 좋아, 다른 언어 같으면 5줄 이상 써야하는 것들을 한 줄로 끝내버리는 편리함이 있으나, 종류가 너무 많아서 한번쯤 정리해놓으면 좋을 것 같았습니다.
이 글은 지금(2021.06.13)이 시작입니다. 새로운 메서드나 연산방법이 있으면 계속 이 글에 업데이트해 나갈 것입니다!😉
String Method
concat
: 인수로 전달한 1개 이상의 문자열과 연결하여 새로운 문자열 반환. 성능상으로는 +
,+=
할당 연산자를 사용하는 것이 더 유리함. 예제) 다음 소스 코드를 완성하여 날짜와 시간을 출력하시오.
출력: 2019/04/26 11:34:278
var year = '2019';
var month = '04';
var day = '26';
var hour = '11';
var minute = '34';
var second = '27';
var result = year.concat('/',month,'/',day,' ',hour,':',minute,':',second);
console.log(result);
indexOf
: 인수로 전달한 문자 또는 문자열을 대상 문자열에서 검색하여 처음 발견된 곳의 index를 반환함. 발견하지 못할 경우 -1을 반환. const str = 'Hello World';
console.log(str.indexOf('or')); // 7
console.log(str.indexOf('or' , 8)); // -1
if (str.indexOf('Hello') !== -1) {
// 문자열 str에 'hello'가 포함되어 있는 경우에 처리할 내용
}
lastIndexOf
: 인수로 전달한 문자 또는 문자열을 대상 문자열에서 역방향부터 검색하여 마지막으로 발견된 곳의 index를 반환. 발견하지 못하면 -1 반환const str = 'Hello World';
console.log(str.lastIndexOf('World')); // 6, 문자열이라면 문자열의 첫 수
console.log(str.lastIndexOf('o', 5)); // 4
console.log(str.lastIndexOf('o', 8)); // 7
replace
: 문자열을 대체하여 새로운 문자나 문자열 반환 const str = 'Hello world';
// 첫번째로 검색된 문자열만 대체하여 새로운 문자열을 반환한다.
console.log(str.replace('world', 'Lee')); // Hello Lee
// 특수한 교체 패턴을 사용할 수 있다. ($& => 검색된 문자열)
console.log(str.replace('world', '<strong>$&</strong>')); // Hello <strong>world</strong> -> <strong>world</strong>으로 해도 되긴 됨.
/* 정규표현식
g(Global): 문자열 내의 모든 패턴을 검색한다.
i(Ignore case): 대소문자를 구별하지 않고 검색한다.
*/
console.log(str.replace(/hello/gi, 'Lee')); // Lee Lee
// 두번째 인수로 치환 함수를 전달할 수 있다.
// camelCase => snake_case
const camelCase = 'helloWorld';
// /.[A-Z]/g => 임의의 1문자와 대문자의 조합을 문자열 전체에서 검색한다.
console.log(camelCase.replace(/.[A-Z]/g, function (match) {
// match : oW => match[0] : o, match[1] : W
return match[0] + '_' + match[1].toLowerCase();
})); // hello_world
// /(.)([A-Z])/g => 1문자와 대문자의 조합
// $1 => (.)
// $2 => ([A-Z])
console.log(camelCase.replace(/(.)([A-Z])/g, '$1_$2').toLowerCase()); // hello_world
// snake_case => camelCase
const snakeCase = 'hello_world';
// /_./g => _와 1문자의 조합을 문자열 전체에서 검색한다.
console.log(snakeCase.replace(/_./g, function (match) {
// match : _w => match[1] : w
return match[1].toUpperCase();
})); // helloWorld
새로운 메서드를 지속적으로 업데이트할 예정입니다. 🤗