반응형
자바스크립트 내의 모든 string method는 immutable 이다.
즉, 원본이 변하지 않는다.
문자열 기본 사용법
str[index]
car str = 'mouse';
cosole.log(str[0]); // 'm'
cosole.log(str[2]); // 'u'
cosole.log(str[10]); // undefined
index로 접근은 가능하지만 쓸 수는 없다. (read-only)
str[0] = 'G';
console.log(str); // 'mouse' not 'Gouse';
문자열 연결 ( Concatenating Strings )
+ 연산자 사용이 가능하다.
string 타입과 다른 타입 사이에 + 연산자를 사용하면, string 형식으로 변환 (toString)
var str1 = 'Hello';
var str2 = "World";
var str3 = '1'
console.log(str1 + str2); // 'HelloWorld'
console.log(str3 + 9); // '19'
str1.concat(str2, str3...);
length PROPERTY
var str = 'HelloWorld';
console.log(str.length); // 10
문자열의 전체 길이를 반환한다.
str.indexOf(searchValue)
arguments : 찾고자 하는 문자열
return value : 처음으로 일치하는 index, 찾고자 하는 문자열이 없으면 -1
lastIndexOf 는 문자열 뒤에서 부터 찾는다.
'Blue Whale'.indexOf('Blue'); // 0
'Blue Whale'.indexOf('blue'); // -1
'Blue Whale'.indexOf('Whale'); // 5
'Blue Whale Whale'.indexOf('Whale'); // 5
'canal'.lastIndexOf('a'); // 3
str.includes(searchValue)도 존재하나, Internet Explorer와 같은 구형 브라우저에서는 작동하지 않음
str.split(seperator)
var str = 'Hello from the other side';
console.log(str.split(' '));
// ['Hello', 'from', 'the', 'other', 'side']
csv형식을 처리할 때 유용하게 사용 가능하다.
str.substring(start, end)
arguments : 시작 index, 끝 index
return value : 시작과 끝 index 사이의 문자열
var str = 'abcdefghij';
console.log(str.substring(0, 3)); // 'abc'
console.log(str.substring(3, 0)); // 'abc'
console.log(str.substring(1, 4)); // 'bcd'
console.log(str.substring(-1, 4)); // 'abcd', 음수는 0으로 취급
console.log(str.substring(0, 20)); // 'avcdefghij', index 범위를 넘을 경우 마지막 index로 취급
str.slice(start, end) 는 substring과 비슷하나, 몇가지 차이가 있다.
str.toLowerCase() / str.toUpperCase() //immutable
arguments : 없음
return value : 대, 소문자로 변환된 문자열
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
반응형
'Code > JavaScript' 카테고리의 다른 글
Javascript 배열 (Array)의 기본 개념, 인덱스(index)와 메소드(method) (0) | 2020.09.20 |
---|---|
Javascript 탬플릿 리터럴(Template literals), 내장 표현식 허용 (0) | 2020.09.13 |
Javascript 조건문 if, 비교 연산자, 논리 연산자 (0) | 2020.09.13 |
Javascript 타입(type)에 따른 작동 방식의 차이 // String(), Number() (0) | 2020.09.13 |
Javascript 함수(function), return 명령문, 함수선언 및 개념 (0) | 2020.09.13 |